2012-07-31 73 views
0

有什麼方法可以將異常映射到django中的HttpResponse對象嗎?Django將異常映射到HttpResponse

例如,我想我自己的「UnauthorizedException」映射到,所以當我的觀點提出了這一例外,而不是自動得到映射到500,某些例外情況可以當作401

回答

4
的HttpResponseForbidden響應對象

如果您實施自己的中間件,可以實現process_exception方法。一個簡單的例子:

from django.http import HttpResponseForbidden 
from app.exceptions import UnauthorizedException 


class UnauthorizedAccessMiddleware(object): 
    def process_exception(self, request, exception): 
     if isinstance(exception, UnauthorizedException): 
      return HttpResponseForbidden("You are not authorized to access that page.")