目前,我有一个这样定义的脚本:
import traceback
import logging
import time
logging.basicConfig(level=loggings.DEBUG)
logger=logging.getLogger(__name__)
if __name__ == '__main__':
try:
main_code()
except Exception as e:
logger.debug(traceback.format_exc())
error = traceback.format_exc()
with smtplib.SMTP("mailhub.global.company.com") as mailServer:
msg = MIMEMultipart('related')
msg['Subject'] = Header(u'Test', 'utf-8')
msg['X-Priority'] = '2'
body = "Delivery Failure, the following exception occurred:\n\n" + str(error)
msg.attach(MIMEText(body, 'plain'))
mailServer.sendmail("email@gmail.com", ["email@gmail.com"], msg.as_string())
mailServer.quit()
print("Exception occurred- delivery failure email sent")
从某种意义上说,这是完美的,如果有错误,我会收到一封带有追溯信息的电子邮件。
在失败的情况下,我尝试向代码添加“重试”,因此它尝试5次,中间间隔5秒,如下所示:
if __name__ == '__main__':
for attempt in range(5):
try:
main_code()
except Exception as e:
print("Error occurred, retrying in 5 seconds!")
time.sleep(5)
continue
else:
break
else:
logger.debug(traceback.format_exc())
error = traceback.format_exc()
with smtplib.SMTP("mailhub.global.company.com") as mailServer:
msg = MIMEMultipart('related')
msg['Subject'] = Header(u'Test', 'utf-8')
msg['X-Priority'] = '2'
body = "Delivery Failure, the following exception occurred:\n\n" + str(error)
msg.attach(MIMEText(body, 'plain'))
mailServer.sendmail("email@gmail.com", ["email@gmail.com"], msg.as_string())
mailServer.quit()
print("Exception occurred- delivery failure email sent")
但是,由于某种原因,当我现在收到传递失败的电子邮件时,它只表示:Delivery Failure, the following exception occurred: NoneType: None
有什么主意如何使回溯到发送的电子邮件中的错误?
答案 0 :(得分:1)
当您离开except
块时,该异常将被“清理”(已销毁),以便在您到达最后一个{{1}时,traceback
模块中的函数无法看到它}块。您可能想将else
移到error = traceback.format_exc()
块中(并将except
传递到error
)。