自定义错误返回
settings
REST_FRAMEWORK = {
# 自定义错误返回
"EXCEPTION_HANDLER": "utils.handler.exception_handler",
}
exceptions(重写错误类)
from rest_framework import status
from rest_framework.exceptions import APIException
class ExtraException(APIException):
def __init__(self, detail=None, ret_code=None, code=None, status_code=status.HTTP_200_OK, msg=None):
"""
detail:如果不是list/dict 就是普通信息,不穿msg
ret_code:状态码
msg:如果detail是list/dict,msg作为提示信息
"""
super().__init__(detail, code)
self.ret_code = ret_code
self.status_code = status_code
self.msg = msg
自定义错误返回方法
from django.http import Http404
from rest_framework import exceptions
from rest_framework.response import Response
from rest_framework.exceptions import ValidationError
from rest_framework.exceptions import Throttled
from rest_framework.exceptions import PermissionDenied
from rest_framework.exceptions import NotAuthenticated
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.views import set_rollback
def exception_handler(exc, context):
if isinstance(exc, Http404):
# 未找到资源,RetrieveModelMixin中
exc = exceptions.NotFound()
exc.ret_code = -1
elif isinstance(exc, PermissionDenied):
# 权限报错
exc = exceptions.PermissionDenied()
exc.ret_code = 1002
elif isinstance(exc, (AuthenticationFailed, NotAuthenticated)):
# 鉴权报错
exc.ret_code = 1003
elif isinstance(exc, Throttled):
# 限流报错
exc.ret_code = 1004
elif isinstance(exc, ValidationError):
# 校验报错
exc.ret_code = 1005
# 只处理drf相关的异常
if isinstance(exc, exceptions.APIException):
headers = {}
if getattr(exc, 'auth_header', None):
headers['WWW-Authenticate'] = exc.auth_header
if getattr(exc, 'wait', None):
headers['Retry-After'] = '%d' % exc.wait
if isinstance(exc.detail, (list, dict)):
code = getattr(exc, 'ret_code', None) or -1
msg = getattr(exc, 'msg', None) or 'error'
data = {'code': code, 'detail': exc.detail, "msg": msg}
else:
code = getattr(exc, 'ret_code', None) or -1
msg = getattr(exc, 'msg', None)
if msg:
data = {'code': code, 'msg': exc.detail, 'detail': msg}
else:
data = {'code': code, 'msg': exc.detail}
set_rollback()
return Response(data, status=exc.status_code, headers=headers)
return None
使用
raise ExtraException(detail=serializer.errors, ret_code=returnCode.VALIDATE_ERROR, msg='校验失败')
raise ExtraException(ret_code=returnCode.VALIDATE_ERROR, detail="修改必须由创建人修改")
本文作者:Sherwin
本文链接:https://www.cnblogs.com/sherwin1995/p/17160472.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步