异常处理 Exceptions

DRF框架的默认异常处理设置如下:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler'
}

默认使用rest_framework.views模块下的exception_handler函数进行异常处理

自定义异常处理

可以自定义异常处理函数,在DRF框架默认异常处理函数的基础上,添加一些其他的异常处理,比如数据库处理
1)自定义异常处理函数

from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework import status
from django.db import DatabaseError

def exception_handler(exc, context):
    # 先调用DRF框架的默认异常处理函数
    response = drf_exception_handler(exc, context)

    if response is None:
        # 补充数据库的异常处理
        if isinstance(exc, DatabaseError):
            response = Response({'detail': '数据库错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

    return response

2)在settings.py配置文件中修改DRF框架的异常处理函数

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'booktest.utils.exceptions.exception_handler'
}

posted @ 2019-08-02 20:27  太虚真人  阅读(339)  评论(0编辑  收藏  举报