Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 465
AlexH Avatar asked Dec 29 '14 22:12

AlexH


2 Answers

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.

like image 165
AlexH Avatar answered Oct 24 '22 04:10

AlexH


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

like image 38
Cartucho Avatar answered Oct 24 '22 05:10

Cartucho