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",
}
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With