在 excepthook 中打印原始异常

Print original exception in excepthook

我正在设置 sys.excepthook 以便我可以记录发生的每个异常。让我们使用以下示例,而不是写入日志:

def excepthook(self, type_, value, traceback):
    print "\n"
    print type_
    print value
    print traceback
    print "\n"

sys.excepthook = self.excepthook

现在假设我创建了一个类型错误,如下所示:

print 3 + str(2)

在没有被捕获的情况下,它进入异常钩子并正确打印出 3 个变量:

<type 'exceptions.TypeError'>
unsupported operand type(s) for +
<traceback object at 0x02BAE800>

我想做的是让它也打印出发送到 excepthook 的完整异常(因此,在本例中为 TypeException)。换句话说,我希望它也显示以下信息)。

Traceback (most recent call last):
  File "testcidnelite.py", line 13, in <module>
    print 3 + str(2)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

如果我添加以下行:

raise

会正常显示异常;但是,它还会显示错误,其中包含术语 raise:

Error in sys.excepthook:
Traceback (most recent call last):
  File "C:\psi-test-automation\Selenium\TestMethods2.py", line 145, in  excepthook
    raise
TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType 

将其更改为:

raise type_

会打印出如下错误:

Error in sys.excepthook:
Traceback (most recent call last):
  File "C:\psi-test-automation\Selenium\TestMethods2.py", line 145, in excepthook
    raise type_
TypeError

Original exception was:
Traceback (most recent call last):
  File "testcidnelite.py", line 13, in <module>
    print 3 + str(2)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

我希望它只打印出第二个块(原始异常)。这可能吗?

您可以使用Python的回溯模块来格式化异常。

from traceback import format_exception

def excepthook(self, type_, value, traceback):
    print format_exception(type_, value, traceback)

sys.excepthook = self.excepthook

查看官方 documentation 了解更多信息和示例。

您可以再次调用系统sys.excepthook

示例代码:

# Created by BaiJiFeiLong@gmail.com at 2022/3/1
import logging
import sys
from sys import excepthook

sys.excepthook = lambda *args: (logging.error("Exception occurred: %s", args[1]), excepthook(*args))
raise RuntimeError("IronChainException")

示例输出:

ERROR:root:Exception occurred: IronChainException
Traceback (most recent call last):
  File "/tmp/example.py", line 7, in <module>
    raise RuntimeError("IronChainException")
RuntimeError: IronChainException