Django rest_framework custom error message

前端 未结 3 702
梦谈多话
梦谈多话 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:53

    You can write custom error handler:

    from rest_framework.views import exception_handler
    
    def custom_exception_handler(exc, context):
        response = exception_handler(exc, context)
        if response is not None:
            response.data['Failure'] = 'Error'
    
        return response
    
    0 讨论(0)
  • 2021-01-15 15:53

    A simple way is to use one of the exception messages, eg NotFound. See docs

    # views.py
    from rest_framework.exceptions import NotFound
    
    class myview(viewsets.ModelViewSet):
        def perform_create(self, serializer):
            raise NotFound("My text here")
    

    That will return a 404 and change the response to your text

    HTTP 404 Not Found
    Allow: GET, POST, HEAD, OPTIONS
    Content-Type: application/json
    Vary: Accept
    {
        "detail": "my text here"
    }
    
    0 讨论(0)
  • 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)

    0 讨论(0)
提交回复
热议问题