【问题标题】:Handling exception through a decorator in Django通过 Django 中的装饰器处理异常
【发布时间】: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


    【解决方案1】:

    这是一个正常的行为:你从装饰器运行 target_function 并且你在其中捕获了异常,所以装饰器看不到它。我认为你必须 raise target_function 中的异常,就像你在装饰器中所做的那样。但是由于你必须在修饰函数之外返回一个Response,这个问题似乎很难解决......

    【讨论】:

      猜你喜欢
      • 2020-01-10
      • 2016-12-14
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      • 2012-03-27
      • 2017-04-14
      相关资源
      最近更新 更多