[Fixed]-DRF – How to handle exception on serializer create()?

22πŸ‘

βœ…

I would probably choose a Validation error if you don’t want to establish custom errors (here DRF errors http://www.django-rest-framework.org/api-guide/exceptions/).

Your error tells you you need to respond with kind of object because if your try fails None is returned.

except (AlreadyFriendsError, user_model.DoesNotExist, AssertionError):
    raise serializers.ValidationError("human readable error message here")

This should fix your requirement.

Some additional tips for your code:

  1. checkout validation and custom DRF validators http://www.django-rest-framework.org/api-guide/validators/. They can help you in similar situations and help to separate your business logic from your serializers
  2. the except hits 3 different Exceptions. To have an easier to use API you should respond with separate error messages to have more context for the client

Leave a comment