将请求数据包含在 Django Rest Framework 自定义异常处理程序响应数据中

Mic*_*ian 4 python django error-handling django-errors django-rest-framework

使用的技术:

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
Run Code Online (Sandbox Code Playgroud)

这会发送基本错误信息,如“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
Run Code Online (Sandbox Code Playgroud)

Rah*_*pta 5

这应该适合你的情况。

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'] = context['request']
        response.data['error'] = response.data.get('detail')
        del response.data['detail']

    return response
Run Code Online (Sandbox Code Playgroud)

request您可以从传递给 的上下文中访问custom_exception_handler。这是在DRF 3.1.0中添加的。另请参阅已解决的 问题。

如果您使用 DRF<3.1,则不会有request异常处理程序的上下文。您可以升级到 DRF 3.1.3(PyPI中的最新版本),然后轻松访问request上下文。

取自DRF 3.1.1源代码:

def get_exception_handler_context(self):
    """
    Returns a dict that is passed through to EXCEPTION_HANDLER,
    as the `context` argument.
    """
    return {
        'view': self,
        'args': getattr(self, 'args', ()),
        'kwargs': getattr(self, 'kwargs', {}),
        'request': getattr(self, 'request', None)
    }
Run Code Online (Sandbox Code Playgroud)

此外,您还需要在settings.py文件中配置异常处理程序。

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}
Run Code Online (Sandbox Code Playgroud)

如果未指定,则'EXCEPTION_HANDLER'设置默认为 REST 框架提供的标准异常处理程序:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
}
Run Code Online (Sandbox Code Playgroud)

笔记:

仅针对引发的异常生成的响应调用异常处理程序。它不会用于视图直接返回的任何响应,例如序列化器验证失败时通用视图返回的 HTTP_400_BAD_REQUEST 响应。