django - Django 自定义异常返回 503 并跳过发送管理员电子邮件
问题描述
我想提出一个自定义异常,它将:
- 返回 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
因为不再有异常跟踪(exc_info),因为异常是在 process_exception 中处理的。
解决方案
附加exc_info
到request
inCustomMiddleware
并在 中访问它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
推荐阅读
- python - Python中的自定义排序顺序
- mysql - 如何在 MacOS 上重置 MySQL 或 MariaDB(使用 brew 安装)?
- python - 将多索引键转换为列
- c# - so I have this loop but I don't understand what does it do so can someone tell me (int i = 0; i <= n; d[i, 0] = i++)
- matplotlib - Matplotlib wont allow minor xticklabels to be written over major labels
- azure - Azure Cron Schedule to trigger every second week on Monday (trigger one Monday and not the other, repeat)
- ios - Alignment in horizontal stack view of label and switch
- dask - dask merge/to csv results in crash
- amazon-web-services - AWS Application Load Balancer (ALB) passing requests to lambda with body base64 encoded?
- php - PDOStatement::bindParam() maximum number of parameters <= 5