[Answered ]-Using ParseError Django REST Framework to return invalid data

0👍

✅

When the exception is raised in the pre_save method(), post_save(), or even in a post() method for the viewclass, it was being handled correctly by Django-REST-Framework. Had I been using curl or similar, the error would have been returned correctly.

This actually is a bug in the browsable API, which is what I was using to test – sending the data using the “Raw data” form. When trying to render the html response, DRF apparently tries to capture the “context” of the post. In this case, it wanted the saved/completed post.

That did not exist, so a Django rendering error was being thrown and that confused me.

When testing using curl, the response was accurate.

Note that putting it in the get_serializer_class() like I did caused it to go outside of the DRF exception handler so Django rendered it correctly and showed the error was being thrown correctly.

2👍

Have a look at APIView‘s handle_exception — this is where DRF processes exceptions raised during the request.

From the docs:

The default implementation handles any subclass of rest_framework.exceptions.APIException, as well as Django’s Http404 and PermissionDenied exceptions, and returns an appropriate error response.

If you need to customize the error responses your API returns you should subclass this method.

So you need to override this to handle ParseError exceptions too.

Also check out the DRF docs on Exceptions.

I hope that helps.

Leave a comment