0

The Django Rest Framework exception handler doesn't seem to be working for me. ValidationErrors are getting turned into 500 responses.

When a ValidationError is raised, it doesn't get converted into a 400.

Traceback (most recent call last):
  File "/example/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/example/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/example/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/example/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/example/.local/lib/python3.6/site-packages/django/views/generic/base.py", line 97, in dispatch
    return handler(request, *args, **kwargs)
  File "/example/app/views.py", line 25, in post
    serializer.is_valid(raise_exception=True)
  File "/example/.local/lib/python3.6/site-packages/rest_framework/serializers.py", line 242, in is_valid
    raise ValidationError(self.errors)
rest_framework.exceptions.ValidationError: {'email': [ErrorDetail(string='Enter a valid email address.', code='invalid')]}
[26/Feb/2020 20:44:54] "POST /login/ HTTP/1.1" 500 84465

In settings.py I have

INSTALLED_APPS = [
    # ...
    'rest_framework',
]

But I get the same behavior whether I have rest_framework in my INSTALLED_APPS or not.

Adding this to settings.py has no effect either:

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'bla',
}

Am I missing something obvious?

1 Answer 1

2

It turns out it depends on the view you're sub-classing while throwing the exception.

I was subclassing View, which did not work:

from rest_framework import views
from rest_framework.exceptions import ValidationError


class LoginView(views.View):
    def post(self, request):
        raise ValidationError()

Switching to using GenericAPIView fixed my issue:

from rest_framework import generics
from rest_framework.exceptions import ValidationError


class LoginView(generics.GenericAPIView):
    def post(self, request):
        raise ValidationError()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.