异常处理 Exceptions
REST framework提供了异常处理,可以出来以下异常:
APIException 所有异常的父类ParseError 解析错误AuthenticationFailed 认证失败NotAuthenticated 尚未认证PermissionDenied 权限决绝NotFound 未找到MethodNotAllowed 请求方式不支持NotAcceptable 要获取的数据格式不支持Throttled 超过限流次数ValidationError 校验失败异常处理设置
DRF框架的默认异常处理设置如下:
REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler' }默认使用rest_framework.views.exception_handler模块下的exception_handler函数进行异常处理。
自定义异常处理
可以在DRF框架异常处理函数的基础上,补充一些其他的异常处理,比如数据库处理:
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: view = context['view'] # 补充数据库的异常处理 if isinstance(exc, DatabaseError): print('[%s]: %s' % (view, type(exc))) response = Response({'detail': '服务器内部错误'}, status=status.HTTP_507_INSUFFICIENT_STORAGE) return response在配置文件中声明自定义的异常处理:
REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'booktest.utils.exceptions.exception_handler' }