app下新建customException.py
内容如下
from rest_framework.response import Response
from rest_framework.views import exception_handler
from common.returnMsg import ReturnMsg
from rest_framework import status
'''
django内置异常
Http404
PermissionDenied
DRF框架异常
APIException - DRF 框架异常的父类,以下为它的子类
NotFound 未找到
PermissionDenied 权限拒绝
ParseError 解析错误
AuthenticationFailed 认证失败
NotAuthenticated 尚未认证
MethodNotAllowed 请求方式不支持
Throttled 超过限流次数
ValidationError 校验失败
NotAcceptable 要获取的数据格式不支持
'''
def CustomException(exc, context):
# 先调用DRF默认的 exception_handler 方法, 对异常进行处理,
# 如果处理成功,会返回一个`Response`类型的对象
response = exception_handler(exc, context)
if response is None:
# 项目出错了,但DRF框架对出错的异常没有处理,
# 可以在此处对异常进行统一处理,比如:保存出错信息到日志文件
view = context['view'] # 出错的视图
error = '服务器内部错误, %s' % exc
return ReturnMsg(code=5001, data={'detail': error},status=status.HTTP_500_INTERNAL_SERVER_ERROR).result()
elif response.status_code ==403:
error = '暂未登录, %s' % exc
return ReturnMsg(code=50002, data={'detail': error}, status=status.HTTP_500_INTERNAL_SERVER_ERROR).result()
return response
在setting.py中新增设置
REST_FRAMEWORK = {
# 异常捕获
'EXCEPTION_HANDLER': 'tboss_server.customException.CustomException',
}
这个时候请求接口如果未登录,则会提示