0

I want to add a sentence to every error message my Python program raise. Something like this:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    raise Exception
  Exception
AN ERROR OCCURRED, PLEASE ASK ABOUT IT ON STACKOVERFLOW!

I mean every exception, including the built-in ones. How can I do this?

stasto
  • 23
  • 5
  • 3
    Why? If it's associated with every excretion, isn't it kind of implicit? That seems like it will add noise more than anything. Is there an end goal that you're striving for? – Carcigenicate Feb 29 '20 at 01:22
  • This won't be pretty, Python's built-in exceptions are, well, built-in/extension types, i.e. they are implemented in C, and so you can't monkeypatch them. – juanpa.arrivillaga Feb 29 '20 at 01:24
  • 2
    You can wrap your whole code with `try` ending with a broad `except Exception as e` then print whatever you want and `raise e`. But seems a bit weird to be honest – Tomerikoo Feb 29 '20 at 01:25
  • 1
    This sounds like a case of the [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) to me. Can you provide some more context for this? – AMC Feb 29 '20 at 02:54

1 Answers1

2

I am not sure if its possible to elegantly change all exception messages.

Here's the next best thing I could come up with. We are going to use decorators.

In general, decorators are like wrappers for functions. There is a good explanation for how they work here: https://youtu.be/7lmCu8wz8ro?t=2720

This is the one I came up with:

def except_message(message=''):
  def inner(f):
    def wrapper(*args, **kwargs):
      try:
        return f(*args, **kwargs)
      except Exception as e:
        raise type(e)(str(e) + "\n" + message).with_traceback(sys.exc_info()[2])
    return wrapper
  return inner

Atop a function that you want to use this decorator on, write @except_message(message='My_message') where 'My_message' is whatever you want the message to be. (It will add it to the end of the exception message)

Example:

@except_message(message='FOUND AN EXCEPTION')
def foo():
    raise Exception()

After it is run, the following is returned by the console:

Traceback (most recent call last):
  File "main.py", line 7, in wrapper
    return f(*args, **kwargs)
  File "main.py", line 15, in foo
    raise Exception()
Exception

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 17, in <module>
    foo()
  File "main.py", line 9, in wrapper
    raise type(e)(str(e) + "\n" + message).with_traceback(sys.exc_info()[2])
  File "main.py", line 7, in wrapper
    return f(*args, **kwargs)
  File "main.py", line 15, in foo
    raise Exception()
Exception:
FOUND AN EXCEPTION

If you only want the message you chose to appear, change in the decorator's function str(e) + "\n" + message to message.

Also, to change all exceptions to this message, you could wrap you code in a function (either by calling it inside a function in a different file or by simply changing the indentation) and then using the decorator.

Credits:

https://stackoverflow.com/a/6062799/5323429

https://stackoverflow.com/a/13898994/5323429

Allan Lago
  • 309
  • 2
  • 14