【发布时间】:2017-09-20 06:23:56
【问题描述】:
我正在尝试在 django 中创建一个错误处理装饰器,并在发生异常时在装饰器中进行日志记录,并将异常引发回装饰函数,然后发送错误 http 响应。
但是当我尝试这样做时,如果在装饰器的异常被抛出后,我在装饰函数中添加了一个 except 块,那么只有装饰函数的 except 块被执行,而装饰器的 except 块被留下未执行。
MyDecorator.py
def log_error(message):
def decorator(target_function):
@functools.wraps(target_function)
def wrapper(*args, **kwargs):
try:
return target_function(*args, **kwargs)
except Exception as e:
print('except block of the decorator')
exceptiontype, exc_obj, exc_tb = sys.exc_info()
filename = traceback.extract_tb(exc_tb)[-2][0]
linenumber = traceback.extract_tb(exc_tb)[-2][1]
mylogger(message=str(e),description='Related to Registration',fileName=filename,lineNumber=linenumber, exceptionType = type(e).__name__)
raise
return wrapper
return decorator
装饰功能
@log_error('message')
def action(self, serializer):
try:
..................
..................
..................
..................
return Response(status=status.HTTP_200_OK, data={
"message":'link sent successfully'})
except Exception as e:
print('except block of the decorated function')
return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR,
data={"message" : 'error sending link'})
这是打印行
修饰函数的块除外
而不是线
装饰器的块除外
如果我从装饰函数中删除了 except 块,那么装饰器的 except 块将被执行。
对于理解如何在装饰器中处理此异常跟踪的任何帮助表示赞赏。
【问题讨论】:
标签: django python-3.x python-decorators