I have a problem with proper handling an exception in Django middleware. My exception:
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
And my Middleware:
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
And this exception throws 500 instead of 403. How can i fix that?
Try to return a HttpResponseForbidden response instead of raising exception
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With