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/166134.html原文链接:https://javaforall.net

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


相关推荐

  • java认证考试试卷_java认证考试试题及答案

    java认证考试试卷_java认证考试试题及答案java认证考试试题及答案故答案为C。12.Whatistheresultafterthefollowingcodeexecutes?1shorts=0x00FD;2byteb=(byte)s;3System.out.println(b);Select1correctanswer:A.Compiletimeerrorinline1B.Comp…

    2022年7月7日
    19
  • 详解Cisco ACS AAA认证

    详解Cisco ACS AAA认证详解CiscoACSAAA认证近来,有些同学会问到关于AAA认证的问题,以及ciscoACS如何使用,那么今天我们就主要来讲一下关于这方面的知识。AAA代表Authentication、Authorization、Accounting,意为认证、授权、记帐,其主要目的是管理哪些用户可以访问服务器,具有访问权的用户可以得到哪些服务,如何…

    2022年5月10日
    40
  • virsh console 进不去虚拟机_virsh 命令

    virsh console 进不去虚拟机_virsh 命令参考自链接http://www.2cto.com/os/201411/354288.html下的文章,感谢作者,自己整理备份,以备查用。问题描述:       先执行命令virshstartmycentos,启动虚拟机。       当执行命令virshconsolemycentos后出现如下显示:       virshconsolemycentos

    2022年8月12日
    4
  • 安装jdk For Windows

    1.下载JDK查看最新:http://www.oracle.com/technetwork/java/javase/downloads/index.html根据操作系统选择合适的JDK进行下载2.运行

    2021年12月22日
    46
  • Invalidate介绍[通俗易懂]

    Invalidate介绍[通俗易懂]1、Invalidate介绍  voidInvalidate(BOOLbErase=TRUE);  该函数的作用是使整个窗口客户区无效。窗口的客户区无效意味着需要重绘,例如,如果一个被其它窗口遮住的窗口变成了前台窗口,那么原来被遮住的部分就是无效的,需要重绘。这时Windows会在应用程序的消息队列中放置WM_PAINT消息。MFC为窗口类提供了WM_PAINT的消息处理函数OnPaint,OnPaint负责重绘窗口。视图类有一些例外,在视图类的OnPaint函数中调用了OnDraw函数,实际

    2025年5月23日
    0
  • nginx rtmp 视频流服务器直播测试

    nginx rtmp 视频流服务器直播测试一、配置1、nginx流媒体服务器下载nginx源码,nginx-rtmp-module源码,先configure“–add-modeule=…”…,再编译安装,教程很多,略……。先增加如下配置.再配置路由器端口映射:二、VLC测试Ffmpeg推流转发rtmp://live.hkstv.hk.lxdns.com/live/hks视…

    2022年10月20日
    0

发表回复

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

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