有没有办法捕捉 Djangohandle_uncaught_exception
并以某种方式通过视图重新路由错误?
我们为 Django 使用我们自己的数据库后端。后端的两个重要特性是我们使用数据库来引发我们希望渗透到前端的异常,并且我们使用 namedtuples 提供了一个惰性行获取器。
当我使用惰性 rowgetter 时,我无法捕获自定义异常,而我在执行标准查询时可以做到这一点。一个示例回溯如下:
ERROR Internal Server Error: /api/b-r-o-k-e-n--t-o-k-e-n/
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py", line 136, in get_response
response = response.render()
...lines removed...
File "/usr/lib/python2.7/dist-packages/django/template/defaulttags.py", line 144, in render
values = list(values)
File "../xmlapi/model/model.py", line 80, in xmlapi_get_location_rota
for i in self.foldquery(query, args, slices):
File "../xmlapi/model/db.py", line 168, in foldquery
self.query(querystring, args)
File "../xmlapi/model/db.py", line 44, in wrapped_fn
raise DBException(e.message.strip())
DBException
Traceback (most recent call last):
File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run
self.result = application(self.environ, self.start_response)
File "/usr/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 241, in __call__
response = self.get_response(request)
File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py", line 179, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
...lines removed...
惰性 rowgetter 的优点是它仅在模板开始渲染时才被调用(我认为)。缺点似乎是我无法在视图中捕获异常以引发,比如420: rate limit exceeded
错误。
由于评估较晚,因此未调用错误处理程序:
try:
rota = self.model.xmlapi_get_location_rota (**kwargs)
except DBException, e:
code, message = [epart.strip() for epart in e.msg.split(':')]
return HttpResponse(message, status=code,
content_type="text/plain")
如果您有任何关于尝试早点抛出此异常而不必加载整个结果集的想法,我将不胜感激。