【发布时间】:2022-11-23 01:44:06
【问题描述】:
例如,当使用 print(ex) 打印异常时,仅打印链中的最后一个异常,我如何才能打印链中的所有异常而不用过多的回溯信息挤满它。
例如:
def test_with_context(context: str, test: int)
try:
assert isinstance(test, int)
assert test > 4, "Test must be greater than 4"
assert test < 6, "Test must be smaller than 6"
exccept AssertionError as ex:
raise ValueError(f"Invalid test for context {context}") from ex
try:
test_with_context("ExampleContext", 8)
except ValueError as ex:
print("Value Test Failed":)
print(ex)
为我提供输出
Value Test Failed
ValueError: Invalid test for context ExampleContext
这有助于向我提供整体上下文,但没有告诉我究竟是什么错误导致了 ValueError。
我想要实现的是:
Value Test Failed
ValueError: Invalid test for context ExampleContext
AssertionError: Test must be smaller than 6
我可以用:
traceback.print_exc()
但这为我提供了完整的格式化回溯、行号和所有信息,这些信息太多了,无法为用户提供一个简单的输入错误。
---
同样,我尝试过使用
exccept AssertionError as ex:
ex.add_note(f"Invalid test for context {context}")
但看起来这些注释根本没有出现在完整的上下文中。
有没有什么办法可以得到一个很好的异常历史记录列表来按顺序打印?
【问题讨论】:
-
你能从
traceback.print_exc()中解析/提取你需要的信息吗? -
您是否探索过任何其他 Traceback 方法/对象?不错 examples in the docs 显示自定义打印格式 - 您是否探索并尝试适应?
-
这些似乎都没有提到或提供处理
raise Exception from Exception语法的解决方案。我不是在完整的回溯之后,我不需要确切地知道每个错误发生的位置,我只是试图使用异常向用户提供有关他们输入失败原因的信息——两个异常处理程序可能是几个堆栈层彼此分开,完整的轨迹最终成为视觉解析的噩梦。就手动解析来自 traceback.print_exc() 的信息而言,这似乎可能会产生一个非常脆弱且依赖于上下文的解决方案。
标签: python python-3.x exception error-handling raise