问题
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.
Thanks, Dave
回答1:
The process_exception
only gets invoked when the view raises an Exception. As 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.
回答2:
As per the documentation the process_exception,
process_exception(self, request, exception)
takes a HttpRequest object, an Exception object raised by the view function as arguments and returns a HttpResponseobject as response.So,it will not be called when the code raises a 500 error(a HttpResponse object).The process_exception will be called only for uncaught exception in the views.
来源:https://stackoverflow.com/questions/6466792/for-a-django-middleware-class-how-can-process-request-work-just-fine-but-proce