首页 > 解决方案 > 如何处理 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。我该如何解决这个问题?

标签: pythondjangodjango-rest-frameworkmiddleware

解决方案


尝试返回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

推荐阅读