DRF异常捕获

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',
}

这个时候请求接口如果未登录,则会提示
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值