因为自己写api定义了一套格式,但是django rest_framework的异常提醒又跟我的不一样,
要么是:
QQ图片20200911221406.png
要么是

{
"detail":"身份错误"
}

实在是不统一!!!
如果不修改,前端调用的时候就得多写点逻辑,或者强迫症极度不适应
于是就有了这篇文章。

我看了下,网上对于这样的情况,没有针对的指出,所以特地的发表这篇问题。

嗯,drf关于异常处理写个了方法

def exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.

    By default we handle the REST framework `APIException`, and also
    Django's built-in `Http404` and `PermissionDenied` exceptions.

    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {'detail': exc.detail}

        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)

    return None

这里出现detail的!!!!

而我们要做的,就是重写异常的方法

REST_FRAMEWORK = {
...
    'EXCEPTION_HANDLER': 'exception.handler.custom_exception_handler',
....
}

然后去获取这个detail,并且删除不必要的提示

from rest_framework.views import exception_handler


def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)
    if response is not None:
        data = response.data.copy()
        response.data.clear()
        text = ''
        for k, v in data.items():
            text += f'{k}: {v}'
        response.data['error'] = text

    return response

经过这样的处理,

就能变成这样的干净
QQ截图20200911221935.png

python

版权属于:染念
作品采用:本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
更新于: 2020年09月12日 16:48
6
发表评论
  1.     Windows 10 /    Google Chrome

    东土大唐前来学习

  2.     Windows 10 /    Google Chrome

    前来学习



180 文章数
673 评论量
4 分类数
184 页面数
已在风雨中度过 7年65天4小时9分
目录
来自 《DRF自定义错误异常替换detail信息》
© 2024 染念Blog
浙ICP备19020194号-1
暗黑模式
暗黑模式
评论
返回顶部
© 2024 染念Blog
浙ICP备19020194号-1
暗黑模式
暗黑模式
评论
返回顶部