drf高级之——自定义全局异常处理

发布时间 2023-12-28 17:05:09作者: wellplayed

自定义全局异常处理

 

drf异常处理交给exception_handler处理了,但是没处理非drf的异常

'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'

 

我们可以重写一个exception_handler方法,处理drf异常和自己的异常

以后只要出现异常,都会走到它

方式如下:

 

第一步:首先创建一个py文件,以 exceptions.py 为例

第二步:导入 exception_handler ,重写方法

from rest_framework.views import exception_handler

 

第三步:书写自定义 common_exception_handler 方法

def common_exception_handler(exc, context):
    # drf的异常,处理了
    res = exception_handler(exc, context)
    if res:  # 有值说明是drf的异常,
        # data = {'detail': exc.detail}
        # return Response(data)
        # {code: 100, msg: 成功}
        detail = res.data.get('detail') or "drf异常,请联系系统管理员"
        return Response({'code': 999, 'msg': detail})
    else: # 如果没值,说明是自己的异常
        return Response({'code': 888, 'msg': '系统异常,请联系系统管理员:%s'%str(exc)})

 

第四步:在settings文件中配置自定义方法

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'app01.exceptions.common_exception_handler',
}

 

以后处理的异常都会走自定义的方法了