我有一组Python脚本,它们以嵌套方式调用函数。对于每个函数,我都有一个try,except语句来捕获每个异常并打印它们。我想发送一封电子邮件警报,其中包含在执行过程中遇到的完整异常序列。示例:
import sys
def SendAlert(ErrorMessage):
try:
#send email alert with error message
#[...]
except:
print(str(sys.exc_info()))
return(sys.exc_info())
def ParentFunction():
try:
#call ChildFunction
ChildResult = ChildFunction()
#do stuff with ChildResult
#[...]
return ParentResult
except:
ErrorMessage = str(sys.exc_info())
print(ErrorMessage)
SendAlert(ErrorMessage)
def ChildFunction():
try:
#do stuff
#[...]
return ChildResult
except:
print(str(sys.exc_info()))
return(sys.exc_info())
#main
if __name__ == '__main__':
Result = ParentFunction()
如果ChildFunction
中嵌套最多的函数出错,上述代码的行为如下:
ChildFunction
遇到异常,它将打印并返回
发送给ParentFunction
的错误消息ParentFunction
将失败,因为ChildResult
包含错误消息而不是有效值ParentFunction
将触发和异常,并在电子邮件警报中发送自己的错误消息除了来自ParentFunction
的错误消息,我希望电子邮件警报包含来自ChildFunction
的错误消息。注意,我希望避免在ParentFunction
的except语句中将ChildResult
变量传递给SendAlert
函数,因为在现实生活中,我的程序有很多嵌套函数,这意味着将每个函数的结果变量传递到except语句中。在
你怎么做到的?有没有一种方法可以访问整个程序触发的完整的错误序列?在
谢谢
您还可以创建一个
custom exception
,它可以接收描述性错误消息并返回它。在下面是一个小例子,您可以在代码中修改和实现它,直到它满足您的需要:
输出:
^{pr2}$您不需要返回使用
sys.exc_info
获得的异常:我们可以重新引发它所以你的例子看起来像
^{pr2}$进一步改进
为了打印完整的错误回溯,我们可以使用^{} 模块
它只是冰山一角,
logging
太棒了,你绝对应该使用它。在进一步阅读
相关问题 更多 >
编程相关推荐