gpt4 book ai didi

python - Django:将错误发送给管理员并将响应返回给用户

转载 作者:太空宇宙 更新时间:2023-11-03 18:38:52 24 4
gpt4 key购买 nike

我已经使用 Django 实现了 JSON API(作为项目的一部分)。有时我会以 JSON 形式向用户返回错误。我想通过电子邮件通过标准错误报告程序通知管理员(例如,当引发未捕获的异常时)。但我也想返回一些 JSON 响应,而不是 500 错误页面。一些元代码可确保一切清晰:

def request_handler(request):
try:
code_that_rises_an_exception()
return response('{"result":"success"}')
except Exception,e:
notify_admin_about_error(e) # <- this function is required
return response('{"result":"error"}')

谢谢!

最佳答案

您可以使用Django Middleware为了这。中间件允许您修改/处理提供给 View 的 Django HttpRequest 对象和 View 返回的 HttpResponse 对象,以及在 View 引发异常时采取操作。您可以用它执行各种任务,例如记录您收到的请求的元数据、错误报告等。Django 调用 process_exception每当 View 引发异常时,您都可以定义 process_exception() 以便在引发异常时向您发送邮件。

class ErrorReportingMiddleware(object):
def process_exception(self, request, exception):
send_mail_to_admin(exception) # you can collect some more information here
return HttpResponse('{"result":"error"}') # this response is returned to the user

将该类添加到该元组末尾的 settings.py 中的 MIDDLEWARE_CLASSES 变量中。

您的 View 将减少为:

def request_handler(request):
code_that_rises_an_exception()
return response('{"result":"success"}')

现在,如果 request_handler 引发异常,Django 将调用 ErrorReportingMiddleware 的 process_exception 方法,该方法将向管理员发送有关异常的邮件,并向浏览器返回 JSON 响应,而不是 500 页面。我将 send_mail_to_admin 实现为异步函数,以便 django 对响应的处理不会因发送邮件而被阻止,并将快速响应返回给用户。

关于python - Django:将错误发送给管理员并将响应返回给用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21001140/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com