Reputation: 23
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?
Upvotes: 0
Views: 953
Reputation: 2988
You could override sys.excepthook
as described in this answer which would then let you print what you want or modify the exception (as in Allan's answer) before passing it to the original sys.__excepthook__
.
This should apply globally meaning you don't have to remember to wrap each function with a decorator.
Upvotes: 1
Reputation: 309
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
Upvotes: 2