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

♀尐吖头ヾ 提交于 2019-12-10 15:06:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!