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方式来处理全局异常

相关推荐
在世修行6 小时前
智学文枢:页面切换与跨页数据预填
python·桌面应用·signal·1024程序员节·pyside·跨页跳转·状态预填
2601_962885726 小时前
如何用 Python 把 K 线重采样成任意周期?
开发语言·python
打工仔折腾 AI6 小时前
在 Ubuntu ARM64 部署 Q1 V3.0 MuJoCo 模型:加载、单步推理与执行器响应解析
linux·运维·人工智能·python·深度学习·ubuntu·性能优化
信誓旦旦的程序猿7 小时前
【Python量化实战宝典 #21】北向资金跟随手册:聪明钱择时信号(Python 可跑)
python·1024程序员节·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
严谨的麻辣烫7 小时前
静态 ISP 代理请求超时怎么排查?Python 与 curl 实战
python·http·requests·1024程序员节·网络排障
KeepRobots9 小时前
11-01 温哥华不回拨:用 60 行 Python 查你的工单系统会不会差一小时(KeepRobots 工程笔记)
python
xiao77mwq9 小时前
你以为 OCR 慢?实测 81.3 s 里全是故障代价:如何把「定格态」消掉,让耗时从 6.5 s 到 13 倍差距显出原形
python
深圳市益普科技有限公司9 小时前
半导体良率管理YMS:良率与设备参数的相关性,先拉哪几组数据
人工智能·python·算法
“AI国潮设计-小江”9 小时前
【AIGC实战】Python+SDXL打造“潮汕英歌舞IP”万能立牌插件,批量生成“发财元宝蛋糕”视觉营销方案(附源码)
开发语言·人工智能·python·prompt·aigc
砚底藏山河10 小时前
python量化实操:冷热分层存储
java·开发语言·python·金融