[Django]-Intercepting a Django 500 error for logging, without creating/serving a custom 500.html

5👍

Instead of making a custom 500 handler, make a custom middleware of your own and implement a process_exception method in it:

import traceback


class Log500ErrorsMiddleware:
    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):
        print('\n----intercepted 500 error stack trace----')
        print(exception)
        print(type(exception))
        tb = exception.__traceback__
        print(traceback.format_exception(type(exception), exception, tb))
        print('----\n')
        return None # Let other middlewares do further processing

Then add it to the MIDDLEWARE setting, all the way at the end, since the middlewares are run in bottom-up order during the response/exception phase, so if you put it last it will always get run (some middleware can decide to short circuit and return a response otherwise, so having anything after it might prevent it from running).

MIDDLEWARE = [
    ...
    'path.to.Log500ErrorsMiddleware',
]

Leave a comment