How to handle an exception in a Django Middleware?

一曲冷凌霜 提交于 2021-01-05 07:03:58

问题


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?


回答1:


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



回答2:


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




回答3:


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',
)


来源:https://stackoverflow.com/questions/56272278/how-to-handle-an-exception-in-a-django-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!