restframework自定义错误捕获

在settings中配置自己的异常处理函数

# rest_framework 异常处理
REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'luffyapi.utils.exceptions.luffy_exception_handler'
}

编写异常处理函数

import logging
from django.db import DataError
# rest_framework 默认使用的异常处理
from rest_framework.views import exception_handler
from rest_framework.response import Response
from rest_framework.status import *

logger = logging.getLogger('django')


def luffy_exception_handler(exc, context):
    """

    :param exc: 错误类型
    :param context: 本次发生异常的上下文[request对象 异常发生的时间 行号 等信息 ]
    :return:
    """
    # 先执行rest_framework的默认异常处理
    response = exception_handler(exc, context)
    if response is None:
        view = context["view"]
        # 这里处理我们自己的异常逻辑
        if isinstance(exc, DataError):
            # 数据库异常
            # 将异常写入到日志文件
            logger.error(
                '[%s] %s' % (view, exc)
            )
            response = Response(
                {'detail': '内部错误'}, status=HTTP_507_INSUFFICIENT_STORAGE
            )

    return response

 

posted on 2021-06-22 22:38  信奉上帝的小和尚  阅读(77)  评论(0编辑  收藏  举报

导航