为什么我的 Django 中间件没有处理 ValueError?

问题描述 投票:0回答:1

我正在实现一个基本视图,该视图引发了

ValueError

from rest_framework.views import APIView

from django.http import HttpResponse

class ThreadView(APIView):


    def get(self, request, *args, **kwargs):


        limit = int(request.GET.get('limit', 10))
            
        if limit < 0:
            raise ValueError("Limit must be a positive number")

        return HttpResponse("OK",200)

我还做了一个简单的中间件:

from django.http import JsonResponse

class ErrorMiddlewareHandler:
    """
    Custom middleware to handle Errors globally and return a standardized JSON response.
    """

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        try:
            # Process the request and pass to the view
            response = self.get_response(request)
        except ValueError as v:
            print("mIDDLEWARE ",v)
            response = JsonResponse({'msg': str(v)}, status=400)  # You can change status as needed
        except Exception as e:
            response = JsonResponse({'msg': "Internal Error occired"}, status=500)
        return response

我已将其注册到

settings.py
:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'assistant_api.middleware.ErrorMiddlewareHandler.ErrorMiddlewareHandler', # <<< This One
]

但是中间件似乎无法处理它:

enter image description here

尽管已注册到中间件中。你知道为什么吗???

python django error-handling
1个回答
0
投票

您可以使用

.process_exception(…)
方法处理异常 [Django-doc]:

class ErrorMiddlewareHandler:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        return self.get_response(request)

    def process_exception(self, request, exception):
        if isinstance(exception, ValueError):
            return JsonResponse({'msg': str(v)}, status=400)
        else:
            return JsonResponse({'msg': 'Internal Error occired'}, status=500)
© www.soinside.com 2019 - 2024. All rights reserved.