我正在实现一个基本视图,该视图引发了
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
]
但是中间件似乎无法处理它:
尽管已注册到中间件中。你知道为什么吗???
.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)