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

(0)
上一篇 2022年7月29日 下午1:46
下一篇 2022年7月29日 下午1:46


相关推荐

  • Java实现水仙花代码「建议收藏」

    Java实现水仙花代码「建议收藏」Java实现水仙花数简单代码//代码如下importjava.util.*;publicclassShuiXianHua{publicstaticvoidmain(String[]args){System.out.println(“判断水仙花数”);inti,j,k=0;//i是个位…

    2025年7月2日
    5
  • @pytest.mark.parametrize_pytest参数化可变参数

    @pytest.mark.parametrize_pytest参数化可变参数前言当某个接口中的一个字段,里面规定的范围为1-5,你5个数字都要单独写一条测试用例,就太麻烦了,这个时候可以使用pytest.mark.parametrize装饰器可以实现测试用例参数化。官方示

    2022年7月31日
    9
  • RSA算法简述

    RSA算法简述52tangzongb+TR/9sbreGJhbKT5U5rQCTUebfRngB0uhNMnvMClf0f/IpPTsM5+7zWJyT9drzVKzV4oR0J8lyMSWepKvv3BR/3Ab6vC8dmo7NDbzuDtLaDLYhYG+bggQNVvuA5C3TolntxdL4+mGZwfd86WoznJM+Y5TO/0C5MSxvaAMTMZuga7yyBKTH4Wl+7GFHDDZqAXmvPHW/Dz0i45vlToz/+E/RnznY5dBhkw3nnNoNsJIutAUDm4T18J

    2022年6月18日
    35
  • 160个练手CrackMe-034

    160个练手CrackMe-0341 无壳 FileKey 类型 2 OD 载入 00 6A00push0x0 hTemplateFil NULL00 push0x80 Attributes NOR

    2025年6月18日
    10
  • Windows11PE安装与分区教程

    Windows11PE安装与分区教程

    2026年3月16日
    2
  • Linux开发在中国[通俗易懂]

    Linux开发在中国[通俗易懂][2004-5-15]  中关村最堵车的白颐路旁的一座公寓里,赵宇一手拿着遥控器,一手指着电视屏幕给客户演示着流媒体的点播效果。作为腾博讯公司的总经理,赵宇已经在Linux圈里面摸爬滚打了五年多。他曾策划发行过Linux光盘,创建过Linux社区,做过Linux杂志主编。现在,他又基于Linux流媒体服务器技术创建了自己的公司。  但…

    2022年10月4日
    5

发表回复

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

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