drf框架中的异常组件

02-04 异常组件

1.异常组件的使用

在settings的drf配置中配置EXCEPTION_HANDLER,指向自定义的exception_handler函数:

# 项目下的settings.py

REST_FRAMEWORK = {
	'EXCEPTION_HANDLER': 'api.utils.exception_handler',
}
# api.utils.exception_handler.py
from rest_framework.response import Response
from rest_framework.views import exception_handler as exc_handler

def exception_handler(exc, context):
    # 调用drf的exception_handler方法,处理客户端的异常
    response = exc_handler(exc, context)
    # 如果返回值为None,说明是服务器异常,drf的exception_handler没处理
 	if response is None:
        return Response(status=500, data={
            "status": 1,
            "exc": f"{exc}",
        })
    return Response(status=response.status_code, data={
        "status": 1,
        "exc": response.data.get("detail")
    })

2.异常组件源码

如果不配置自定义异常函数,系统默认走drf中的exception_handler方法:

# exception_handler
def exception_handler(exc, context):

    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)
	# 如果是服务端错误,会返回None
    return None
posted @ 2019-11-19 22:57  17vv  阅读(312)  评论(0编辑  收藏  举报