给定文件errors.py
:
from traceback import format_tb, extract_tb
class MyError(Exception):
def __init__(self, message):
self.message = message
class MySecondError(Exception):
def __init__(self, message):
self.message = message
try:
try:
raise MyError("Something specific has happened")
except Exception as error:
raise MySecondError("Something general has happened") from error
except Exception as error:
print("".join(format_tb(error.__traceback__)))
运行python errors.py
时,输出为:
File "errors.py", line 15, in <module>
raise MySecondError("Something general has happened") from error
这方面的主要问题是,只有“链”中的“最高”错误的回溯(MySecondError
),没有关于包装错误的信息(MyError
)
如果我删除最后的try/except
包装器以便不捕获链式错误,我会得到更好的输出:
Traceback (most recent call last):
File "exceptions.py", line 14, in <module>
raise MyError("Something specific has happened")
__main__.MyError: Something specific has happened
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "exceptions.py", line 16, in <module>
raise MySecondError("Something general has happened") from error
__main__.MySecondError: Something general has happened
它具有完整错误链和连接行(Traceback (most recent call last):
,The above exception was the direct cause of the following exception:
)的回溯和每个错误的字符串表示
理想情况下,我希望捕获这些输出行以将它们定向到其他位置(例如记录器)
我的一个解决方案是迭代error.__context__
并手动添加连词:
except Exception as error:
inner_error = error
while inner_error:
if inner_error is not error:
print("\nThe above exception was the direct cause of the following exception:\n")
print("Traceback (most recent call last):")
print("".join(format_tb(inner_error.__traceback__) + [ str(error) ]))
inner_error = inner_error.__context__
这是可行的,但它是黑客的,我更愿意使用一些标准的库模块,它已经处理了这个问题
您想使用^{} 函数:
给出:
如果指定
chain=False
,此函数将不打印连接异常,而只打印最后一个异常相关问题 更多 >
编程相关推荐