使用的技术:
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