【发布时间】:2017-07-15 18:42:34
【问题描述】:
我的项目中有一个常见的情况,我使用自定义异常来包装内置的异常场景,例如:
# meaningless here but in other situations its useful...
try:
5/0
except ZeroDivisionError as e:
raise MyCustomException(msg=str(e))
还有一个如下所示的通用异常处理程序:
@app.errorhandler(Exception) # this decorator is flask related - ignore it
def handle_error(error):
if isinstance(error, MyCustomException):
# some code
# I only want MyCustomException traceback
else:
# some other code
exc_stack = traceback.format_exc(limit=5)
这里的已知问题是我得到了两个异常回溯,而在 if-case 中我只想要最后一个。
据我所知,这个问题有两种解决方案。
第一个解决方法(使用from None):
try:
5/0
except ZeroDivisionError as e:
raise MyCustomException(msg=str(e)) from None # python3
第二种解决方法(在引发第二个异常之前调用回溯)
try:
5/0
except ZeroDivisionError as e:
tracb = traceback.format_exc(limit=5)
raise MyCustomException(msg=str(e), tracb_msg=tracb)
无需在异常处理程序中调用traceback.format_exc(),只需使用传递给实例的tracb_msg。显然第一个解决方法更简单。
我的问题:
这两种方法都会在代码中重新出现(重复代码/技巧)数十次,每次我都会提出MyCustomException。有没有人想出一个技巧来在处理函数中处理这个一次?
【问题讨论】:
标签: python python-3.x exception-handling traceback