Chiefir
Chiefir

Reputation: 2671

How to handle an exception in a Django Middleware?

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?

Upvotes: 4

Views: 6353

Answers (3)

JPG
JPG

Reputation: 88439

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

Upvotes: 12

ruddra
ruddra

Reputation: 51948

Instead of using Middleware, I think you should use 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

And add this in DEFAULT_PERMISSION_CLASSES to make it available for every API view.

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

Upvotes: 2

Jota
Jota

Reputation: 737

Try with this exception:

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'

I think you can't do that, read this: https://groups.google.com/forum/#!topic/django-developers/-ncPqVzF8W8

Upvotes: 1

Related Questions