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="修改必须由创建人修改")