AlexH
AlexH

Reputation: 327

How can I catch a database error in django rest framework?

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?

Upvotes: 7

Views: 2304

Answers (2)

Cartucho
Cartucho

Reputation: 3319

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

Upvotes: 5

AlexH
AlexH

Reputation: 327

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.

Upvotes: 5

Related Questions