django统一处理异常

自定义异常处理中间件

1、先创建自定义异常类

该类必须包含两个方法init,call

init用于初始化

call用于处理请求

python 复制代码
from django.http import JsonResponse


class GlobalExceptionMiddleware:

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        try:
            response = self.get_response(request)
        except Exception as e:
            print(type(e))
            return JsonResponse({
                'code': -1,
                'msg': str(e)
            })
        return response

1)call方法是为了让类的实例像函数一样被调用,如GlobalExceptionMiddleware(xxx),就会直接执行类中的call方法

2)get_response 是一个可调用对象(通常是一个函数),它的作用是处理请求,调用下一个中间件或视图函数,并生成响应

3)get_response 的返回值是一个 HttpResponse 对象,表示处理后的响应

4)当你调用 self.get_response(request) ,如果还有其他中间件,get_response 会调用下一个中间件,如果没有更多中间件,get_response 会调用最终的视图函数来处理请求

2、注册中间件到settings文件中

中间件注册是类级别的

python 复制代码
MIDDLEWARE = [
    # 'django.middleware.security.SecurityMiddleware',
    # 'django.contrib.sessions.middleware.SessionMiddleware',
    # 'django.middleware.common.CommonMiddleware',
    # # 'django.middleware.csrf.CsrfViewMiddleware',
    # #'django.contrib.auth.middleware.AuthenticationMiddleware',
    # #'django.contrib.messages.middleware.MessageMiddleware',
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'middlewares.my_middleware.GlobalExceptionMiddleware',
]

3、settings文件中添加该配置

DEBUG_PROPAGATE_EXCEPTIONS = True #该配置是让中间件处理异常,避免django自己处理异常

继承MiddlewareMixin重写process_exception

1、创建自定义中间件类继承MiddlewareMixin重写process_exception方法

python 复制代码
from django.utils.deprecation import MiddlewareMixin
from django.http import JsonResponse

class MyMiddleware(MiddlewareMixin):

    # 当视图中出现异常时,会捕获到
    def process_exception(self, request, exception):
        return JsonResponse({'code': -1, 'msg': str(exception)})

2、注册自定义中间件到settings中

python 复制代码
MIDDLEWARE = [
    # 'django.middleware.security.SecurityMiddleware',
    # 'django.contrib.sessions.middleware.SessionMiddleware',
    # 'django.middleware.common.CommonMiddleware',
    # # 'django.middleware.csrf.CsrfViewMiddleware',
    # #'django.contrib.auth.middleware.AuthenticationMiddleware',
    # #'django.contrib.messages.middleware.MessageMiddleware',
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'middlewares.my_middleware.MyMiddleware',
]

3、可以不指定DEBUG_PROPAGATE_EXCEPTIONS = True

注意:该方式只能处理视图中触发的异常,如果是视图之外的异常如中间件调用出现的异常则处理不了,只能使用第一种重写call方式来处理全局异常

相关推荐
YMWM_4 分钟前
python3继承使用
开发语言·python
JMchen1235 分钟前
AI编程与软件工程的学科融合:构建新一代智能驱动开发方法学
驱动开发·python·软件工程·ai编程
亓才孓39 分钟前
[Class类的应用]反射的理解
开发语言·python
小镇敲码人1 小时前
深入剖析华为CANN框架下的Ops-CV仓库:从入门到实战指南
c++·python·华为·cann
摘星编程1 小时前
深入理解CANN ops-nn BatchNormalization算子:训练加速的关键技术
python
魔芋红茶1 小时前
Python 项目版本控制
开发语言·python
lili-felicity1 小时前
CANN批处理优化技巧:从动态批处理到流水线并行
人工智能·python
一个有梦有戏的人1 小时前
Python3基础:进阶基础,筑牢编程底层能力
后端·python
摘星编程2 小时前
解析CANN ops-nn中的Transpose算子:张量维度变换的高效实现
python
Liekkas Kono2 小时前
RapidOCR Python 贡献指南
开发语言·python·rapidocr