gpt4 book ai didi

python - 重构错误处理并在 Python 中获得正确的堆栈跟踪

转载 作者:行者123 更新时间:2023-11-28 16:40:10 25 4
gpt4 key购买 nike

我有很多这样的代码:

try:
# do a lot of stuff
except StuffError as e:
log.exception(e):
send_mail_to_admin()
raise e

对于 DRY,我想将其重构为:

def post_mortem(log, e):
log.exception(e):
send_mail_to_admin()
# some other stuff
raise e

然后做:

try:
# do a lot of stuff
except StuffError as e:
post_mortem(log, e)

现在的问题是我没有得到正确的堆栈跟踪,因为异常是从另一个文件引发的。

如何获得与第一个代码相同的堆栈跟踪?

最佳答案

同时传递 exc_info() 信息,作为这样的参数之一

post_mortem(log, e, sys.exc_info()[2])

并且在post_mortem

def post_mortem(log, e, traceBack):
traceback.print_tb(traceBack)

要获取整个堆栈跟踪,您可以像本例中所示那样做

import traceback, sys

def post_mortem(log, e, tb):
print "".join(traceback.format_list(traceback.extract_stack()[:-2]) + [traceback.format_tb(tb)[0]])

def throwError():
try:
raise NameError("I don't like your name")
except NameError as e:
post_mortem("", e, sys.exc_info()[2])

def callThrowError():
throwError()

callThrowError()

输出

  File "/home/thefourtheye/Desktop/Test.py", line 15, in <module>
callThrowError()
File "/home/thefourtheye/Desktop/Test.py", line 13, in callThrowError
throwError()
File "/home/thefourtheye/Desktop/Test.py", line 8, in throwError
raise NameError("I don't like your name")

关于python - 重构错误处理并在 Python 中获得正确的堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20376105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com