I am Implementing a Basic view that raises a 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)
And I made a simple middleware as well:
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
I registered it into 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
]
But it seem middleware not to be able to handle it:
Despite being registered into middlewares. Do you know why???
You handle exceptions with the .process_exception(…)
method [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(exception))}, status=400)
else:
return JsonResponse({'msg': 'Internal Error occired'}, status=500)