django自定义异常处理

1.在utils目录下创建exceptions.py文件,并编写自定义异常处理方法

from django.db import DatabaseError
from rest_framework.response import Response
from rest_framework.views import exception_handler
from rest_framework import status
from redis import RedisError
import logging
log = logging.getLogger("django")

def custom_exception_handler(exc, context):
    """
    自定义异常处理
    :param exc: 本次请求发生的异常信息
    :param context: 本次请求发送异常的执行上下文[ 本次请求的request对象,异常发送的时间,行号等...]
    :return: Response响应对象
    """
    response = exception_handler(exc, context)

    if response is None:
        """当response结果为None时,则当前程序运行的结果有2种可能: 
          1. 程序真的没有报错!
          2. 程序报错了,但是drf框架不识别!
        """
        view = context["view"]
        if isinstance(exc, DatabaseError) or isinstance(exc, RedisError):
            """数据库异常"""
            log.error('[%s] %s' % (view, exc))
            return Response("系统内部存储错误!",  status=status.HTTP_507_INSUFFICIENT_STORAGE)

    return response

2.在settings/dev.py文件中添加自定义异常处理模块

REST_FRAMEWORK = {
    # 异常处理
    'EXCEPTION_HANDLER': 'yd_api.utils.exceptions.custom_exception_handler',
}

版权声明:本文为xutengfei999原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。