Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why ValueError is not handled upon my Django Middleware?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

enter image description here

Despite being registered into middlewares. Do you know why???

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading