How can I catch database error in django rest framework?

I have a unique constraint for a database field. When the duplicate is sent, I would like to avoid sending a 500 response. How can I catch this error in DRF and return a 4XX response instead?

+3


source to share


2 answers


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

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.

+3


source


If you want this just for this view to 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

+1


source







All Articles