Praful Bagai
Praful Bagai

Reputation: 17382

Over-ride DRF custom exception response

I want to send error_codes while sending the response back to the client, in case of an error!!

So, I've a form where params a and b is required. If any of the param is not POSTed, then DRF serializer sends back a response saying This field is required. I want to add the error code to the response as well for the client to identify. Different errors different error codes.

So, I wrote my own custom exception handler. It goes like this.

response = exception_handler(exc, context)
if response is not None:
    error = {
        'error_code': error_code,  # Need to identify the error code, based on the type of fail response.
        'errors': response.data
        }
    return Response(error, status=http_code)
return response

The problem I'm facing is that I need to identify the type of exception received, so that I can send the error_code accordingly. How can I achieve this?

Upvotes: 0

Views: 562

Answers (1)

Satendra
Satendra

Reputation: 6865

REST framework's views handle various exceptions, and deal with returning appropriate error responses.

The handled exceptions are:

  • APIException raised inside REST framework.
  • Django's Http404
  • Django's PermissionDenied exception.

You can identify the type of exception received by status

from rest_framework import exceptions, status
response = exception_handler(exc, context)

if response is not None:
   if response.status == status.HTTP_404_NOT_FOUND:
      # Django's Http404
   elif response.status == status.HTTP_403_FORBIDDEN:
      # PermissionDenied exception
   else:
      # APIException raised 

Also most error responses will include a key detail in the body of the response.

You can check it and set custom error codes.

response = exception_handler(exc, context)

if response is not None:
    # identify the type of exception received, detail can be text, list or dictionary of items.
    if response.data.detail == 'some text':
       error_code = 111
    elif more_conditions:
       ...

Reference: http://www.django-rest-framework.org/api-guide/exceptions/

Upvotes: 1

Related Questions