今天来总结下如何处理drf的异常处理
1:定义一个路由测试
path('error/',views.errorAPIView.as_view({'get':'list'}))
注意不要写错了,否则会报错set
image.png
2:在根目录下建立一个exceptions.py文件,定义如下配置
from rest_framework.views import exception_handler as drf_exception_handler
from django.db import DatabaseError
from rest_framework.response import Response
from rest_framework import status
def custom_exception_handler(exc, context):
"""
自定义异常处理函数
:param exc: 异常对象,本次发生的异常对象
:param context: 字典,异常出现时的执行上下文环境
:return:
"""
# 先让drf进行异常判断
response = drf_exception_handler(exc, context)
# 判断response对象是否为None
if response is None:
"""出现drf不能处理的异常"""
if isinstance(exc, DatabaseError):
view = context.get("view")
print('数据库报错,[%s]: %s' % (view, exc))
return Response({"detail": "服务器内部错误!"}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
if isinstance(exc, ZeroDivisionError):
view = context.get("view")
print("0不能作为除数! [%s]: %s" % (view, exc))
return Response({"detail": "服务器内部错误!"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return response
### REST framework定义的异常
'''
APIException使用drf中所有异常的父类,他的子类有以下:
- ParseError 解析错误
- AuthenticationFailed 认证失败
- NotAuthenticated 尚未认证
- PermissionDenied 权限受限
- NotFound 未找到
- MethodNotAllowed 请求方式不支持
- NotAcceptable 要获取的数据格式不支持
- Throttled 超过限流次数
- ValidationError 校验失败
也就是说,很多的没有在上面列出来的异常,就需要我们在自定义异常中自己处理了。
'''
启动的时候,报这个错误
image.png
image.png
所以我们按照提示修改源码如下
image.png
3:加个视图
#测试数学计算异常
class errorAPIView(ViewSet):
@action(methods=['get'],detail=False,url_path='error')
def list(self,request):
10 / 0
return Response('测试异常。。。。')
4:成功启动了,加上这个配置,否则会报这个错误,看不懂
image.png
# 异常处理
'EXCEPTION_HANDLER': 'exceptions.custom_exception_handler',
5:再次启动
image.png
OK,大功告成~~~~