【发布时间】:2015-08-27 10:41:20
【问题描述】:
使用的技术:
http://www.django-rest-framework.org
例外情况: http://www.django-rest-framework.org/api-guide/exceptions/
在自定义 exceptions.py 文件中包含 rest_framework 默认示例:
from rest_framework.views import exception_handler
import sys
def custom_exception_handler(exc, context=None):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc)
# Now add the HTTP status code to the response and rename detail to error
if response is not None:
response.data['status_code'] = response.status_code
response.data['request'] = request
response.data['error'] = response.data.get('detail')
del response.data['detail']
return response
这会发送“Http404”等基本错误信息,但不会发送请求数据,例如 IP 地址等。
将我的请求添加到响应中的最佳方式是什么?提前致谢。
更新(并已解决):
因此,我最初尝试使用 DjangoRestFramework 2.4.x 解决此问题,但该版本没有自定义异常处理程序的请求或上下文数据选项。升级到 3.1.3 可以轻松地将数据添加到响应中。新代码现在看起来像这样(使用版本 3.1.3):
def custom_exception_handler(exc, request):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, request)
# Send error to rollbar
rollbar.report_exc_info(sys.exc_info(), request)
# Now add the HTTP status code to the response and rename detail to error
if response is not None:
response.data['status_code'] = response.status_code
response.data['error'] = response.data.get('detail')
del response.data['detail']
return response
【问题讨论】:
-
请检查
response = exception_handler(exc)的缩进。对吗? -
谢谢拉胡尔 - 是的,它是正确的 - 我在这里粘贴的方式看起来不对
标签: python django error-handling django-rest-framework django-errors