返回顶部

Django rest framework ----异常处理 Exceptions

REST framework提供了异常处理,我们可以自定义异常处理函数。

官方文档

https://www.django-rest-framework.org/api-guide/exceptions/

在配置文件中配置日志

setting.py

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,  # 是否禁用已经存在的日志器
    'formatters': {  # 日志信息显示的格式
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(lineno)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(module)s %(lineno)d %(message)s'
        },
    },
    'filters': {  # 对日志进行过滤
        'require_debug_true': {  # django在debug模式下才输出日志
            '()': 'django.utils.log.RequireDebugTrue',
        },
    },
    'handlers': {  # 日志处理方法
        'console': {  # 向终端中输出日志
            'level': 'INFO',
            'filters': ['require_debug_true'],
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'file': {  # 向文件中输出日志
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(BASE_DIR, "logs/meiduo.log"),  # 日志文件的位置
            'maxBytes': 300 * 1024 * 1024,
            'backupCount': 10,
            'formatter': 'verbose'
        },
    },
    'loggers': {  # 日志器
        'django': {  # 定义了一个名为django的日志器
            'handlers': ['console', 'file'],  # 可以同时向终端与文件中输出日志
            'propagate': True,  # 是否继续传递日志信息
            'level': 'INFO',  # 日志器接收的最低日志级别
        },
    }
}

 

 

DRFDemo/utils/exceptions.py

from rest_framework.views import exception_handler
 
def custom_exception_handler(exc, context):
    # 先调用REST framework默认的异常处理方法获得标准错误响应对象
    response = exception_handler(exc, context)
 
    # 在此处补充自定义的异常处理
    if response is not None:
        response.data['status_code'] = response.status_code
 
    return response

在配置文件中声明自定义的异常处理  

REST_FRAMEWORK = {
  'EXCEPTION_HANDLER': 'DRFDemo.utils.custom_exception_handler'
}

  

如果未声明,会采用默认的方式,如下

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'exceptions.custom_exception_handler'
}

例如:

补充上处理关于数据库的异常

from django.db import DatabaseError
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import exception_handler
 
 
def custom_exception_handler(exc, context):
    # 先调用REST framework默认的异常处理方法获得标准错误响应对象
    response = exception_handler(exc, context)
 
    # 在此处补充自定义的异常处理
    if response is None:
        view = context['view']
        if isinstance(exc, DatabaseError):
            print('[%s]: %s' % (view, exc))
            response = Response({'detail': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
 
    return response 

 

完整代码如下

from rest_framework.views import exception_handler as drf_exception_handler
import logging
from django.db import DatabaseError
from redis.exceptions import RedisError
from rest_framework.response import Response
from rest_framework import status

# 获取在配置文件中定义的logger,用来记录日志
logger = logging.getLogger('django')

def exception_handler(exc, context):
    """
    自定义异常处理
    :param exc: 异常
    :param context: 抛出异常的上下文
    :return: Response响应对象
    """
    # 调用drf框架原生的异常处理方法
    response = drf_exception_handler(exc, context)

    if response is None:
        view = context['view']
        if isinstance(exc, DatabaseError) or isinstance(exc, RedisError):
            # 数据库异常
            logger.error('[%s] %s' % (view, exc))
            response = Response({'message': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE)

    return response
DRFDemo/utils/exceptions.py

 

 

代码中模拟一个异常:  

from django.db import DatabaseError
class BookInfoViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, GenericViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoModelSerializer
    # authentication_classes = (SessionAuthentication, BasicAuthentication)
    # permission_classes = (IsAuthenticated,)
    filter_fields = ("btitle", "bread")
    # pagination_class = LargeResultsSetPagination
    pagination_class = LimitOffsetPagination
 
    def get_permissions(self):
        if action == "get":
            return [IsAuthenticated()]
        else:
            return [AllowAny()]
 
    @action(methods=["GET"], detail=False)
    def latest(self, request):
        raise DatabaseError()
        book = BookInfo.objects.latest("id")
        serializer = self.get_serializer(book)
        return Response(serializer.data)

  

访问:

REST framework定义的异常

APIException 所有异常的父类
ParseError 解析错误
AuthenticationFailed 认证失败
NotAuthenticated 尚未认证
PermissionDenied 权限决绝
NotFound 未找到
MethodNotAllowed 请求方式不支持
NotAcceptable 要获取的数据格式不支持
Throttled 超过限流次数
ValidationError 校验失败

  

自定义一个捕获数据库查询不到的异常

import logging

from django.core.exceptions import ObjectDoesNotExist
from rest_framework.exceptions import NotFound
from rest_framework.views import exception_handler as old_exception_handler

logger = logging.getLogger(__name__)


def exception_handler(exc, context):
    logger.exception('Uncaught Exception')
    if isinstance(exc, ObjectDoesNotExist):
        exc = NotFound()
    return old_exception_handler(
        exc, context
    )

  

 

posted @ 2018-11-26 22:35  Crazymagic  阅读(3183)  评论(0编辑  收藏  举报