For the Django middleware class, how does the process_request process work fine, but process_exception is not a call?

I created my own middleware class in Django, which worked very well until recently. It is strange that process_request is still called just fine, but even when the 500 response is an internal server error, process_exception is not raised at all. Why?

It doesn’t matter if I declare my middleware class the first or last entry in the list of installed middleware in the settings file.

Thanks Dave

+4
source share
3 answers

process_exception is only triggered when an Exception view appears . As the comment says

If the view throws an exception, run it through the exception middleware,
and if the exception middleware returns a response, use this.
Otherwise, re-raise the exception.

Exceptions caused by incorrect configuration, import error, process_request and process_view cannot be detected and handled by process_exception handlers.

To check if your process_exception working, raise an Exception in the view after you make sure that it works well.

There is no direct relationship between process_request and process_exception ; they are handlers for different purposes and are called at different stages. Any exception was thrown after the process_request , successfully executed and before the submission, was not caught and processed by the process_exception as said.

+7
source

According to the documentation of process_exception,

 process_exception(self, request, exception) 

takes an HttpRequest object, an Exception object created by the view function as arguments, and returns an HttpResponse object as an answer. Thus, it will not be called when the code raises a 500 error (HttpResponse object). Exception_process is only called for an uncaught exception in views.

+2
source

How can we allow the exceptions that occurred in process_request to catch process_exception

 def process_request(self, request): if session: user_id = Session(session=session).user_id if not user_id: raise HTTPError(401) request.current_user = user_id return None 

exception cannot be caught using process_exception

0
source

All Articles