【问题标题】:How to print the __str__ representation of the entire traceback如何打印整个回溯的 __str__ 表示
【发布时间】: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


【解决方案1】:

我提出了一个我不太喜欢的解决方案,但它可以完成工作:

def cause_stack(exception: BaseException) -> List[BaseException]:
    if exception.__cause__ is None:
        return [exception]
    else:
        return [exception] + cause_stack(exception.__cause__)


def format_causes(exception: BaseException) -> str:
    return "
 - caused by -
".join([str(cause) for cause in cause_stack(exception)])

因为每个异常的原因都存储在 .__cause__ dunder 属性下,递归搜索可以按顺序为您提供每个原因的列表,然后我通过将它们与“原因”字符串连接在一起来格式化。

不是很满意它作为一个解决方案 - 感觉不是很 pythonic,使用递归,这对于较大的堆栈可能会有问题并且它不像人们希望的那样优雅,但它现在满足了我的需求。

【讨论】:

    猜你喜欢
    • 2012-05-10
    • 2010-09-27
    • 1970-01-01
    • 2019-05-08
    • 2011-05-19
    • 1970-01-01
    • 2014-01-07
    • 2013-12-21
    • 2011-02-07
    相关资源
    最近更新 更多