I've created my own middleware class in Django that was working just fine until recently. The strange thing is that process_request still gets called just fine, but even when the response is 500 - internal server error, process_exception is not called at all. Why?
It makes no difference whether I declare my middleware class as the first or the last entry in the list of installed middleware in the settings file.
The process_exception
only gets invoked when the view raises an Exception
. As it says in the comment:
If the view raised an exception, run it through exception middleware, and if the exception middleware returns a response, use that. Otherwise, reraise the exception.
Exceptions raised by misconfiguration, importing error, process_request
and process_view
cannot be caught and feed to process_exception
handlers.
To test whether your process_exception
works, raise an Exception in the view after you ensure it works well.
There is not direct relationship between process_request
and process_exception
. They are handlers for different purposes and get invoked at different stages. Any Exception been raised after the process_request
that executed successfully and before the view, will not be caught and processed by process_exception
as said.
As per the documentation for process_exception,
process_exception(self, request, exception) takes an HttpRequest object, an Exception object raised by the view function as arguments and returns an HttpResponseobject as response. So, it will not be called when the code raises a 500 error (an HttpResponse object). The process_exception will be called only for uncaught exceptions in the views.
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