DRF之异常处理

步骤

  第一步:写一个函数

复制代码
from rest_framework.views import exception_handler  # 默认没有配置,出了异常会走它
from rest_framework.response import Response
def common_exception_handler(exc, context):
    # 第一步,先执行原来的exception_handler
    # 第一种情况,返回Response对象,这表示已经处理了异常,它只处理APIExcepiton的异常,第二种情况,返回None,表示没有处理
    res = exception_handler(exc, context)
    if res:  # exception_handler 已经处理了,暂时先不处理了
        # 998:APIExcepiton
        # res=Response(data={'code':998,'msg':'服务器异常,请联系系统管理员'})
        res = Response(data={'code': 998, 'msg': res.data.get('detail', '服务器异常,请联系系统管理员')})
    else:
        # 999:出了APIExcepiton外的异常
        # res=Response(data={'code':999,'msg':'服务器异常,请联系系统管理员'})
        res = Response(data={'code': 999, 'msg': str(exc)})

    # 注意:咱们在这里,可以记录日志---》只要走到这,说明程序报错了,记录日志,以后查日志---》尽量详细
    # 出错时间,错误原因,哪个视图类出了错,什么请求地址,什么请求方式出了错
    request = context.get('request')  # 这个request是当次请求的request对象
    view = context.get('view')  # 这个viewt是当次执行的视图类对象
    print('错误原因:%s,错误视图类:%s,请求地址:%s,请求方式:%s' % (str(exc), str(view), request.path, request.method))
    return res
复制代码

  第二步:把函数配置在配置文件中

      REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'app01.exception.common_exception_handler' # 再出异常,会执行这个函数
}

  自己写一个视图类

复制代码
# 全局异常
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.exceptions import APIException


class TsetView(APIView):
    def get(self, request):
        # 第一种,程序出错
        # l =[1,2,3]
        # print(l[999])
        # 第二种,主动抛异常
        # raise Exception('我错了')
        # 第三种,主动抛APIException异常
        raise APIException('APIException我错了')
        return Response('ok')
复制代码

 

posted @   那就凑个整吧  阅读(112)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示