process_exception(self, request, exception) 函數有兩個參數,exception 是視圖函數異常產生的 Exception 對象
process_exception 函數的執行順序是按照 settings.py 中設置的中間件的順序的倒序執行
process_exception 函數只在視圖函數中出現異常的時候才執行,它返回的值可以是 None,也可以是一個 HttpResponse 對象
如果返回 None,則繼續由下一個中間件的 process_exception 方法來處理異常
如果返回 HttpResponse,將調用中間件中的 process_response 方法
middleware_test.py:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | from django.utils.deprecation import MiddlewareMixin from django.shortcuts import HttpResponse, renderclass Test(MiddlewareMixin):def process_request(self, request):print("這是一個中間件111 --> test11")def process_exception(self, request, exception):print("這里是 Test1的 process_exception")print(exception)return render(request, "index.html")class Test2(MiddlewareMixin):def process_request(self, request):print("這是一個中間件 --> test2")def process_exception(self, request, exception):print("這里是 Test2 的 process_exception")print(exception) |
views.py:
1 2 3 4 5 6 7 |
? ?
|
訪問,http://127.0.0.1:8000/two/index/
?