Django(50)drf异常模块源码分析

Django(50)drf异常模块源码分析异常模块源码入口APIView类中dispatch方法中的:response=self.handle_exception(exc)源码分析我们点击handle_exception跳转,查看该

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

异常模块源码入口

APIView类中dispatch方法中的:response = self.handle_exception(exc)
 

源码分析

我们点击handle_exception跳转,查看该方法源码

def handle_exception(self, exc):
    """
    Handle any exception that occurs, by returning an appropriate response,
    or re-raising the error.
    """
    # 判断异常类型是否是没有认证的类型,最后返回403状态码
    if isinstance(exc, (exceptions.NotAuthenticated,
                        exceptions.AuthenticationFailed)):
        # WWW-Authenticate header for 401 responses, else coerce to 403
        auth_header = self.get_authenticate_header(self.request)

        if auth_header:
            exc.auth_header = auth_header
        else:
            exc.status_code = status.HTTP_403_FORBIDDEN
    
    # 获取异常的方法
    exception_handler = self.get_exception_handler()
    
    # 获取异常的上下文 
    context = self.get_exception_handler_context()

    # 返回异常响应
    response = exception_handler(exc, context)
    
    # 如果响应为内容为空,则抛出异常
    if response is None:
        self.raise_uncaught_exception(exc)

    response.exception = True
    return response

以上源码最为关键的一句就在于exception_handler = self.get_exception_handler(),我们可以点击查看该方法源码

def get_exception_handler(self):
    """
    Returns the exception handler that this view uses.
    """
    return self.settings.EXCEPTION_HANDLER

该方法返回该视图的异常处理方法,从返回的内容,我们可以知道,该方法在settings文件中有个默认值,进入settings可查看到

'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler',

异常处理的默认方法就是views下的exception_handler方法,我们再进入查看该方法源码

def exception_handler(exc, context):
    """
    Returns the response that should be used for any given exception.

    By default we handle the REST framework `APIException`, and also
    Django's built-in `Http404` and `PermissionDenied` exceptions.

    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """
    # 判断异常是否是404
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()

    # 判断异常是否是没有权限
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()

    # 判断异常是否是drf的基类异常,该异常提供了状态码和异常字段detail
    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
        
        # 判断detail是否是list类型或dict类型
        if isinstance(exc.detail, (list, dict)):
            data = exc.detail
        else:
            data = {'detail': exc.detail}

        set_rollback()
        return Response(data, status=exc.status_code, headers=headers)

    return None

从上述代码我们可以知道,当response返回为None时,是不会返回异常信息,而是直接抛出异常,所以我们可以自定义异常类
 

自定义异常

在我们的app目录下,创建utils包,并创建exceptions文件,并写入如下源码:

from rest_framework.response import Response
from rest_framework.views import exception_handler as drf_exception_handler


def exception_handler(exc, context):
    response = drf_exception_handler(exc, context)
    if response is None:
        print(f"{context['view']} - {context['request'].method} - {exc}")
        return Response(status=500, data="服务器错误")
    return response

最后我们将默认异常信息配置改为自己的配置即可,在settings文件中写入如下配置

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'drf_app.utils.exceptions.exception_handler',
}

以后碰到response响应为None的时候,我们就会抛出服务器错误的异常信息
 

总结

为什么要自定义异常模块?

  1. 所有经过drfAPIView视图类产生的异常,都可以提供异常处理方案
  2. drf默认提供了异常处理方案(rest_framework.views.exception_handler),但是处理范围有限
  3. drf提供的处理方案两种,处理了返回异常现象,没处理返回None(后续就是服务器抛异常给前台)
  4. 自定义异常的目的就是解决drf没有处理的异常,让前台得到合理的异常信息返回,后台记录异常具体信息
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/165428.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 16G kingston U盘 解除写保护[通俗易懂]

    16G kingston U盘 解除写保护[通俗易懂]前些天买的16Gkingstonu盘忽然有了写保护,但是拆开u盘又没有看到有写保护开关。纠结加郁闷。然后一天后又忽然发生了电脑无法识别U盘,连盘符也读不出来了。里面好多资料全无,彻底让我伤心了,

    2025年10月16日
    5
  • 手写一个简单的mybatis框架

    手写一个简单的mybatis框架

    2021年8月3日
    65
  • linux下安装部署eureka_Linux部署jboss

    linux下安装部署eureka_Linux部署jboss系列文章目录前言网上搜索了一箩筐安装部署redis的文章,成功部署安装了,方便以后用的着,现在记录下一、下载Redis进入Redis官网找到下载地址点击进入第一种方法:下载压缩包这里我使用的是secureCRT工具连接服务器,上传文件需要使用rz命令xshell工具可忽略步骤#yum自动安装yuminstalllrzsz#yum自动安装完成后输入rz选中下载好的redis.tar.gz包单击上传第二种方法:链接下载Redis右击鼠

    2022年10月5日
    6
  • Spring集成MyBaties中sqlSessionFactory的创建[通俗易懂]

    Spring集成MyBaties中sqlSessionFactory的创建[通俗易懂]Spring的核心思想就是IOC(InversionOfControl),中文意思就是控制反转,将创建对象的任务交由工厂来处理,同时还可以管理类与类之间的关系,从而提出了依赖注入的概念。先来了解对象的分类:1.简单对象:可以通过new的方式创建的对象,例如UserServiceImle、User类等2.复杂对象:不能通过new的方式创建的对象,例如sqlSessionFact…

    2022年5月18日
    39
  • AWVS10.5&12超详细使用教程

    AWVS10.5&12超详细使用教程AWVS介绍awvs

    2025年5月27日
    4
  • android打开相册选择图片_安卓音频

    android打开相册选择图片_安卓音频Buttonclickevent:Intentintent=newIntent(Intent.ACTION_PICK,android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);startActivityForResult(intent,REQUEST_VIDEO_CODE);打开方式有两种ac

    2025年12月5日
    5

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号