Handle error of a specific time raised at any point

38 Views Asked by At

Occasionally we are getting OperationalError: FATAL and we have no idea why. I want to handle this error wherever it happens in the application and send me a personal email. I would also like to set up a system command call to inspect the database activity (I know this is a bad idea but it's the only thing I can think of to try to figure out why this is happening).

How can I do this? Summarized: catch an error of a specific type raised at any point and handle it in a custom and granular way.

1

There are 1 best solutions below

1
Hevlastka On BEST ANSWER

You can create an middleware to handle your exception. See https://docs.djangoproject.com/en/2.2/topics/http/middleware/#process-exception

For example

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.',
                '[email protected]',
                ['[email protected]'],
                fail_silently=False,
            )
            return RedirectToRefererResponse(request)