python - 如何处理 Django 中间件中的异常?
问题描述
我在 Django 中间件中正确处理异常时遇到问题。我的例外:
from rest_framework.exceptions import APIException
from rest_framework.status import HTTP_403_FORBIDDEN
class MyProfileAuthorizationError(APIException):
def __init__(self, msg):
APIException.__init__(self, msg)
self.status_code = HTTP_403_FORBIDDEN
self.message = msg
还有我的中间件:
class PatchRequestUserWithProfile:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request, *args, **kwargs):
patch_request_for_nonanon_user(request)
if not request.user.profile:
raise MyProfileAuthorizationError("You are not allowed to use this profile.")
response = self.get_response(request)
return response
这个异常抛出 500 而不是 403。我该如何解决这个问题?
解决方案
尝试返回HttpResponseForbidden
响应而不是引发异常
from django.http import HttpResponseForbidden
class PatchRequestUserWithProfile:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request, *args, **kwargs):
patch_request_for_nonanon_user(request)
if not request.user.profile:
return HttpResponseForbidden("You are not allowed to use this profile.")
response = self.get_response(request)
return response
推荐阅读
- google-cloud-platform - 无法公开 GCP 存储桶
- c# - C# Parallel.ForEach 在长迭代中阻塞
- html - Ionic 在页面中使用页面并设置属性
- html - 如何在左侧,右侧,顶部和底部的另一个div中制作div
- python - 在 Windows 中更改 Python 中的颜色输出
- css - 我是否正确理解 z-index 的级别?
- python-3.x - python计数熊猫系列值高于值X的次数
- regex - 如何匹配包含子字符串的模式
- python - 使用 scikit-learn 的 WhiteKernel 进行高斯过程回归
- python - 在 7z 存档中读取巨大的 xml