如何处理 Django 中间件中的异常?

How to handle an exception in a Django Middleware?

我在正确处理 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。我该如何解决?

我认为你应该使用 permissions:

而不是使用中间件
from rest_framework import permissions

class CustomAccessPermission(permissions.BasePermission):
    message = 'You are not allowed to use this profile.'

    def has_permission(self, request, view):
       if not request.user.profile:
           return False
       return True

并将其添加到 DEFAULT_PERMISSION_CLASSES 中,使其可用于每个 API 视图。

'DEFAULT_PERMISSION_CLASSES': (
   'path.to.CustomAccessPermission',
)

试试这个例外:

from rest_framework.exceptions import APIException

class MyProfileAuthorizationError(APIException):
    status_code = 403
    default_detail = 'You are not allowed to use this profile'
    default_code = 'forbidden'

我认为你不能那样做,请阅读:https://groups.google.com/forum/#!topic/django-developers/-ncPqVzF8W8

尝试return一个HttpResponseForbidden响应而不是引发异常

<b>from django.http import HttpResponseForbidden</b>


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:
            <b>return HttpResponseForbidden("You are not allowed to use this profile.")</b>

        response = self.get_response(request)
        return response