Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For a Django middleware class, how can process_request work just fine, but process_exception not be calls?

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.

like image 979
Trindaz Avatar asked Jun 24 '11 10:06

Trindaz


2 Answers

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.

like image 54
okm Avatar answered Nov 15 '22 07:11

okm


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.

like image 21
Vivek S Avatar answered Nov 15 '22 06:11

Vivek S