DRF之异常处理组件

一. 异常处理 Exceptions

看一个简单的示例

class APIError(Exception):
    pass

class Student2APIView(APIView):
    def get(self,request,pk):
        try:
            instance = Student.objects.get(pk=pk)
        except Student.DoesNotExist:
            raise APIError('自定义API错误')
            return Response({
    
    "message":"访问的商品已经下架~"})

        serializer = StudentModelSerializer(instance=instance)
        return Response(serializer.data)

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

可以创建一个utils文件夹,里面放一个exceptions.py文件,名字随便写,然后写下面的内容

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context): #自定义的错误处理函数
  	”“”
    	exc错误对象
      context 异常发生时的一些上下文信息
    “”“
    # 先调用REST framework默认的异常处理方法获得标准错误响应对象
    response = exception_handler(exc, context) #这个函数是drf提供的,它处理了一些错误,但是如果它处理不了的,它会返回None,所以,如果是None的话,我们需要自己来处理错误

    # 在此处补充自定义的异常处理
    if response is None:
      	if isinstance(exc,APIError)
        #这里就可以记录错误信息了,一般记录到文件中,可以使用日志系统来进行记录
        # return Respose({'msg':'自定义API错误了'})
        response.data['status_code'] = response.status_code

    return response

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

REST_FRAMEWORK = {
    
    
    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
}

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

rest_frame/settings.py

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

例如:

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

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):
    response = drf_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

REST framework定义的异常

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

猜你喜欢

转载自blog.csdn.net/qq_45066628/article/details/109561125
今日推荐