【问题标题】:How to change the error message for all exceptions in Python?如何更改 Python 中所有异常的错误消息?
【发布时间】:2020-02-29 01:21:00
【问题描述】:

我想在我的 Python 程序引发的每条错误消息中添加一个句子。像这样的:

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

我指的是所有异常,包括内置异常。我该怎么做?

【问题讨论】:

  • 为什么?如果它与每一种排泄物有关,那不是隐含的吗?这似乎会比任何东西都增加噪音。你有一个最终目标吗?
  • 这不太好,Python 的内置异常是,嗯,内置/扩展类型,即它们是用 C 实现的,所以你不能对其进行猴子补丁。
  • 您可以用try 以宽泛的except Exception as e 结尾来包装整个代码,然后打印您想要的任何内容和raise e。但说实话似乎有点奇怪
  • 对我来说这听起来像是XY Problem 的情况。您能否为此提供更多背景信息?

标签: python python-3.x exception


【解决方案1】:

我不确定是否可以优雅地更改所有异常消息。

这是我能想到的下一个最好的方法。 我们将使用装饰器。

一般来说,装饰器就像函数的包装器。 这里有一个很好的解释它们是如何工作的: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

【讨论】:

    猜你喜欢
    • 2021-07-25
    • 2014-01-22
    • 2012-03-09
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 2020-09-02
    • 1970-01-01
    相关资源
    最近更新 更多