Issue
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?
Solution
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
Answered By - Allan Lago
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.