【问题标题】:Django custom exception to return 503 and skip sending admin emailDjango 自定义异常返回 503 并跳过发送管理员电子邮件
【发布时间】:2021-11-11 05:59:52
【问题描述】:

我想提出一个自定义异常,它将:

  • 返回 503 状态
  • 不发送 Django 管理员电子邮件

我可以做其中之一,但不能同时做:

  • 返回 503 状态:通过使用 DRF APIException 或自定义异常处理程序来处理响应,但我不会获取日志记录中的异常类型进行过滤。
  • 不发送电子邮件:通过检查自定义电子邮件处理程序类中的异常类型,但这会返回 500。

通过添加自定义中间件处理 503 的代码示例:

class CustomMiddleware(MiddlewareMixin):
    def process_exception(self, request, exception):
        if isinstance(exception, MyCustomException):
            return JsonResponse({"detail": "Error try later"}, status=503)

不发送电子邮件的代码示例:

class CustomAdminEmailHandler(AdminEmailHandler):
    def emit(self, record):
        ...
        reporter = ExceptionReporter(request, is_email=True, *exc_info)
        if reporter.exc_type and issubclass(reporter.exc_type, MyCustomException):
            return

Django 为任何 5xx 状态响应发送电子邮件。当我使用中间件时,我无法过滤 reporter.exc_type,因为在 process_exception 中处理了异常,因此不再有异常跟踪 (exc_info)。

【问题讨论】:

    标签: django exception django-rest-framework


    【解决方案1】:

    exc_info 附加到CustomMiddleware 中的request 并在CustomAdminEmailHandler 中访问它。

    class CustomMiddleware(MiddlewareMixin):
        def process_exception(self, request, exception):
            if isinstance(exception, MyCustomException):
                # For CustomAdminEmailHandler      # Add this
                request.exc_info = sys.exc_info()  # Add this
                return JsonResponse({"detail": "Error try later"}, status=503)
    
    class CustomAdminEmailHandler(log.AdminEmailHandler):
        def emit(self, record):
            request = record.request
            if record.exc_info:
                exc_info = record.exc_info
            elif hasattr(request, 'exc_info'):  # Add this
                # From CustomMiddleware         # Add this
                exc_info = request.exc_info     # Add this
            else:
                exc_info = (None, record.getMessage(), None)
            reporter = ExceptionReporter(request, is_email=True, *exc_info)
            if reporter.exc_type and issubclass(reporter.exc_type, MyCustomException):
                return
    

    【讨论】:

    • 谢谢,按要求工作。
    猜你喜欢
    • 2010-11-27
    • 2012-11-08
    • 2013-03-01
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 2015-08-25
    相关资源
    最近更新 更多