处理在任何时候引发的特定时间的错误

Handle error of a specific time raised at any point

偶尔我们会得到 OperationalError: FATAL,我们不知道为什么。我想在应用程序中发生的任何地方处理这个错误,并给我发一封个人电子邮件。我还想设置一个系统命令调用来检查数据库 activity(我知道这是个坏主意,但这是我唯一能想到的试图弄清楚为什么会这样的事情)。

我该怎么做?总结:捕获在任何时候出现的特定类型的错误,并以自定义和精细的方式处理它。

您可以创建一个中间件来处理您的异常。参见 https://docs.djangoproject.com/en/2.2/topics/http/middleware/#process-exception

例如

from django.utils.deprecation import MiddlewareMixin
from django.db import OperationalError
from django.core.mail import send_mail
from django.http import HttpResponseRedirect

class RedirectToRefererResponse(HttpResponseRedirect):
    def __init__(self, request, *args, **kwargs):
        redirect_to = request.META.get('HTTP_REFERER', '/')
        super(RedirectToRefererResponse, self).__init__(
            redirect_to, *args, **kwargs)

class HandleOperationalErrorMiddleware(MiddlewareMixin):
    def process_exception(self, request, exception):
        if isinstance(exception, OperationalError):

            send_mail(
                'Subject here',
                'Here is the message.',
                'from@example.com',
                ['to@example.com'],
                fail_silently=False,
            )
            return RedirectToRefererResponse(request)