MhmdRizk
MhmdRizk

Reputation: 1721

Raising a custom 400 bad request in a Rest API using django and django rest framework

I want to return a custom error when a HTTP 400 Error is raised.

this is my model :

class User(models.Model):
      fullname = models.CharField(max_length=100)
      phone = models.CharField(max_length=50, unique=True)
      password = models.CharField(max_length=50, default='SOME STRING')

this is my serializer class :

class UserSerializer(serializers.ModelSerializer):
      class Meta:
           model = User
           fields = ('id', 'fullname', 'phone', 'password')

this is my class in the views class :

 class RegisterUsers(generics.CreateAPIView):
.
.
.
 serializer = UserSerializer(data={
            "fullname": fullname,
            "phone": phone,
            "password": password
        }
    )

          if not serializer.is_valid(raise_exception=True):
              return

if I try to register with the same number twice, a 400 bad request error is raised like the screenshot below :

enter image description here

I want to catch the error and parse it in to a custom response that looks like that :

enter image description here

can anyone help me with this issue ? thanks in advance.

Upvotes: 2

Views: 4783

Answers (1)

aman kumar
aman kumar

Reputation: 3156

You can override the DRF custom exception handler method:

from rest_framework.views import exception_handler
from rest_framework.exceptions import ValidationError


def base_exception_handler(exc, context):
  # Call DRF's default exception handler first,
  # to get the standard error response.
  response = exception_handler(exc, context)

  # check that a ValidationError exception is raised
  if isinstance(exc, ValidationError): 
    # This is where you would prepare the 'custom_error_response'
    # and set the custom response data on response object
    response.data = custom_error_response 

  return response

To enable your custom handler, add the EXCEPTION_HANDLER setting in your settings file:

REST_FRAMEWORK = {
'PAGE_SIZE': 20,
'EXCEPTION_HANDLER': 'path.to.your.module.base_exception_handler',

'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework.authentication.TokenAuthentication',
    'rest_framework.authentication.SessionAuthentication'
)

}

Upvotes: 4

Related Questions