我不确定是否可以优雅地更改所有异常消息。
这是我能想到的下一个最好的方法。
我们将使用装饰器。
一般来说,装饰器就像函数的包装器。
这里有一个很好的解释它们是如何工作的:https://youtu.be/7lmCu8wz8ro?t=2720
这是我想出的:
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
在你想使用这个装饰器的函数顶部,写@except_message(message='My_message'),其中'My_message'是你想要的消息。 (它会将其添加到异常消息的末尾)
例子:
@except_message(message='FOUND AN EXCEPTION')
def foo():
raise Exception()
运行后,控制台返回以下内容:
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
如果您只想显示您选择的消息,请将装饰器的函数 str(e) + "\n" + message 更改为 message。
此外,要更改此消息的所有异常,您可以将代码包装在一个函数中(通过在不同文件中的函数内调用它或通过简单地更改缩进),然后使用装饰器。
学分:
https://stackoverflow.com/a/6062799/5323429
https://stackoverflow.com/a/13898994/5323429