下面用test_demo的例子来说明
def catch_exception(func):
@wraps(func)
def get_except(*args,**kw):
try:
return func(*args,**kw)
except Exception as e:
logger.write_msg(ERROR,f'{func.__name__}方法出现异常,异常原因:{e}')
return get_except
#test_demo
@catch_exception
def demo(num):
num = num/0
return num
test=demo(1)
print(test)
打印结果:
2022-12-14 17:17:02,447 - logger - ERROR - demo方法出现异常,异常原因:division by zero
None
主要的实现就是利用装饰器,catch_exception函数会捕抓异常并打印出现异常的函数方法名称和异常原因,将所可能报错的函数都放在这个装饰器函数内执行,只需在函数加上catch_exception装饰器,方便查看异常信息。