DRF自定义错误异常替换detail信息

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

要么是

{
"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

经过这样的处理,

就能变成这样的干净

上一篇:如何使用pathlib优雅地抛弃open写入
下一篇:没有了