如何处理Django中间件中的异常? [英] How to handle an exception in a Django Middleware?
本文介绍了如何处理Django中间件中的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在正确处理Django中间件中的异常时遇到问题.我的例外:
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
还有我的中间件:
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.我该如何解决?
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
这篇关于如何处理Django中间件中的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文