maxk
maxk

Reputation: 642

django exception handler middleware and handler500

I have a django application with handler500 set. I want to add custom exception handler to it. I create a middleware which handles process exception:

Django calls process_exception() when a view raises an exception. process_exception() should return either None or an HttpResponse object. If it returns an HttpResponse object, the response will be returned to the browser. Otherwise, default exception handling kicks in.

https://docs.djangoproject.com/en/dev/topics/http/middleware/?from=olddocs#process-exception

My ErrorMiddleware looks like:

class ErrorMiddleware(object):
    def process_exception(self, request, exception):
        try:
            #logic goes here
        except Exception:
            pass
        return None

My settings looks like:

MIDDLEWARE_CLASSES = (
    'my.error.ErrorMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
)
DEBUG = False

In this case, my browser never gets a response from page with exception. Though without my middleware in the list, I get handler500 working correctly.

I want default exception handling mechanism to be executed, without explicitly calling handler500 view in my middleware.

UPD:

handler500 module looks like this:

#imports ....

def custom_500(request):
    """ Return an error ID (hash) that can be provided to support """
    return render(request, '500.html', {
        'timestamp': datetime.datetime.now().isoformat(),
        'diagcode': "hello",
        }
    )

Upvotes: 3

Views: 9110

Answers (1)

Simon
Simon

Reputation: 12478

Try moving your middleware to the bottom of the MIDDLEWARE_CLASSES stack so it's the first piece of middleware that gets to handle the request on its way out to the client. I believe Django has already caught your exception and rendered its own error 500 page if you put it last.

Upvotes: 5

Related Questions