You need to enable JavaScript to run this app. Django REST自定义中间件缺少cookie时如何返回500而非KeyError
优惠活动
大模型
产品
解决方案
定价
更多

Django REST自定义中间件缺少cookie时如何返回500而非KeyError

解决方案

你只需要在现有异常捕获逻辑基础上新增KeyError的捕获分支,缺失cookie时直接返回500响应即可,具体调整如下:

  • 第一步:先导入Django内置的500响应类(如果需要返回JSON格式错误可自行替换为JsonResponse)
from django.http import HttpResponseServerError
# 若需要返回JSON格式的500响应可以用下面这句
# from django.http import JsonResponse
  • 第二步:在现有except分支后新增KeyError的捕获逻辑,捕获到异常时直接返回500响应
    调整后的完整中间件代码:
import jwt
from django.http import HttpResponseServerError

class AuthMiddleware:
    def __init__(self, get_response=None):
        self.get_response = get_response

    def __call__(self, request):
        if request.path == '/api/auth/profile/':
            try:
                myCookie = request.COOKIES['my_cookie']
                # 处理cookie的业务逻辑
                return self.get_response(request)
            except jwt.ExpiredSignatureError:
                # 处理jwt过期的业务逻辑
                return self.get_response(request)
            except KeyError:
                # 捕获cookie缺失的异常,直接返回500响应
                return HttpResponseServerError()
                # 如果要返回JSON格式的错误,替换为下面的代码
                # return JsonResponse({"msg": "缺少必要的认证cookie"}, status=500)
        # 非目标路径直接放行
        return self.get_response(request)

注意:原代码中使用//作为注释符号不符合Python语法,实际使用时需要替换为#
如果你需要自定义500响应的内容,可以修改HttpResponseServerError的入参,或者使用JsonResponse指定status=500返回结构化错误信息

内容的提问来源于stack exchange,提问作者forest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 01:06:04