如何在基于类的视图中捕获Django模板期间的特定异常?
我有一个自定义异常ImmediateHttpResponse,它旨在在我的基于类的视图中立即重定向.我试过了:
def dispatch(self, *args, **kwargs):
try:
return super(AppConnectionsView, self).dispatch(*args, **kwargs)
except ImmediateHttpResponse as e:
return HttpResponseRedirect(e.response)
我试图捕获的异常是在模板标记中引发的,因此似乎异常被django的模板调试拦截,我得到模板渲染错误HttpResponseRedirect没有提供异常.我仍然想调试我的模板,而不是在引发HttpResponseRedirect时.
请保留所有关于不在模板标签中引发错误的评论…我有一个非常好的理由.
最佳答案 如果你真的不惜任何代价去做,这是一个简单的解决方案:
def dispatch(self, *args, **kwargs):
response = super(AppConnectionsView, self).dispatch(*args, **kwargs)
try:
response.render()
except ImmediateHttpResponse as e:
return HttpResponseRedirect(e.response)
return response
您无法在视图中捕获渲染错误的原因是因为尽管在视图中创建了响应,但它实际上是由BaseHandler
渲染的,它会适当地处理所有错误.上述解决方案的缺点是它将根据请求呈现模板两次.
能够捕获自定义错误的唯一其他方法是自定义BaseHandler(或者它的派生类,如WSGIHandler),这显然会消除双重渲染问题.
假设你正在使用wsgi,你可能应该:)你可以这样做:
import django
from django.utils import six
from django.core.handlers.wsgi import WSGIHandler as DjangoWSGIHandler
from my_app.exceptions import ImmediateHttpResponse
class WSGIHandler(DjangoWSGIHandler):
def handle_uncaught_exception(self, request, resolver, exc_info):
(type, value, traceback) = exc_info
if type is not None and issubclass(type, ImmediateHttpResponse):
six.reraise(*exc_info)
return super(WSGIHandler, self).handle_uncaught_exception(
request, resolver, exc_info)
def get_wsgi_application():
django.setup()
return WSGIHandler()
现在你可以在wsgi.py中使用这个函数:
application = get_wsgi_application()