Django: catch exceptions and custom error handling

24th January, 2020

If you are using Django, at one point you will definitely want to have the DEBUG mode type reporting from production server as well. Django does very well in reporting the errors in the DEBUG mode and it will be very convenient to have such feature in production as well.  Moreover one can also wish to have such alerting in Slack or Microsoft Teams channel using their Incoming Webhook feature which you can integrate in their channels.

There are already some tools existing such as sentry and more you will find here as well: https://djangopackages.org/grids/g/error-handling/

But when even a simple script can do it for you then why bother installing more packages. Below I show you how to do it:

  1. Create a script called error_handler.py anywhere in the project directory (preferably in the main app directory) and add the following:

    from django.http import HttpResponse
    from django.conf import settings
    import traceback
    
    
    class ErrorHandlerMiddleware:
    
        def __init__(self, get_response):
            self.get_response = get_response
    
        def __call__(self, request):
            response = self.get_response(request)
            return response
    
        def process_exception(self, request, exception):
            if not settings.DEBUG:
                if exception:
                    # Format your message here
                    message = "**{url}**\n\n{error}\n\n````{tb}````".format(
                        url=request.build_absolute_uri(),
                        error=repr(exception),
                        tb=traceback.format_exc()
                    )
                    # Do now whatever with this message
                    # e.g. requests.post(<slack channel/teams channel>, data=message)
                    
                return HttpResponse("Error processing the request.", status=500)​

     

  2. Add the path to this class in the MIDDLEWARE section in the settings.py file of your Django project (at the last).

That's it. This middleware will get executed during each of your requests and will check if you are in DEBUG and if there is an exception, this middleware will then create a message for you :) .