引发异常并返回响应

时间:2019-04-21 14:45:13

标签: django exception django-rest-framework django-serializer

我需要在序列化器的validate()方法内引发异常。所以我做了下面的事情,

class SampleSerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = SampleModel

    def validate(self, attrs):
        foo_value = attrs['foo']
        if foo_value > 100:
            raise ValueError("foo_value cant be grater than 100")
        return attrs

它引发了一个异常,但作为 服务器错误

如何引发异常并安全地向API响应返回一些消息?

1 个答案:

答案 0 :(得分:3)

您应该改为提出ValidationError

class SampleSerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = SampleModel

    def validate(self, attrs):
        foo_value = attrs['foo']
        if foo_value > 100:
            raise serializers.ValidationError("foo_value cant be grater than 100")
        return attrs

然后,如documentation中所述,默认情况下将引发HTTP 400 Bad请求响应。