Django rest_framework custom error message

前端 未结 3 742
梦谈多话
梦谈多话 2021-01-15 15:27

I have a API endpoint where it will do input validation using rest_framework\'s serializer.is_valid() where it will return custom error message and response.

3条回答
  •  半阙折子戏
    2021-01-15 15:55

    Create a Custom Exception class as,

    from rest_framework.exceptions import PermissionDenied
    from rest_framework import status
    
    
    class MyCustomExcpetion(PermissionDenied):
        status_code = status.HTTP_400_BAD_REQUEST
        default_detail = "Custom Exception Message"
        default_code = 'invalid'
    
        def __init__(self, detail, status_code=None):
            self.detail = detail
            if status_code is not None:
                self.status_code = status_code
    


    Why I'm inherrited from PermissionDenied exception class ??
    see this SO post -- Why DRF ValidationError always returns 400

    Then in your serializer, raise exceptions as,

    class SampleSerializer(serializers.ModelSerializer):
        class Meta:
            fields = '__all__'
            model = SampleModel
    
        def validate_age(self, age):  # field level validation
            if age > 10:
                raise MyCustomExcpetion(detail={"Failure": "error"}, status_code=status.HTTP_400_BAD_REQUEST)
            return age
    
        def validate(self, attrs): # object level validation
            if some_condition:
                raise MyCustomExcpetion(detail={"your": "exception", "some_other": "key"}, status_code=status.HTTP_410_GONE)
            return attrs
    


    age and name are two fields of SampleModel class


    Response will be like this


    By using this method,
    1. You can customize the JSON Response
    2. You can return any status codes
    3. You don't need to pass True in serializer.is_valid() method (This is not reccomended)

提交回复
热议问题