7

I have a unique constraint on a database field. When a duplicate is submitted I'd like to avoid sending a 500 response. How can I catch this error in DRF and return a 4XX response instead?

1

2 Answers 2

5

I knew I needed to put a try/except block around something, but I didn't know what. I looked at the DRF code, and I saw that generics.ListCreateAPIView has a method called create. I wrote a new function inside my class called the parent create which has the same signature as the one I inherited, which called create, and I put the try/except around this function.

In the end it looks like this:

class MyModelList(generics.ListCreateAPIView):
    def get_queryset(self):
        return MyModel.objects.all()
    def create(self, request, *args, **kwargs):
        try:
            return super(MyModelList, self).create(request, *args, **kwargs)
        except IntegrityError:
            raise CustomUniqueException
    serializer_class = MyModelSerializer

I hope this helps someone.

Sign up to request clarification or add additional context in comments.

1 Comment

While this method works, if you find yourself repeating it often you'd be better served by @Cartucho's answer about using a custom exception handler.
5

If you want this only for this view override handle_exception:

class MyAPIView(APIView):
  ...

  def handle_exception(self, exc):
      """
      Handle any exception that occurs, by returning an appropriate
      response,or re-raising the error.
      """
      ...

To handle it for all views, you can define a global exception handler, see here: http://www.django-rest-framework.org/api-guide/exceptions

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.