Django rest_framework自定义错误消息

时间:2018-08-03 04:17:21

标签: django django-rest-framework

我有一个API端点,它将使用rest_framework的serializer.is_valid()进行输入验证,并返回自定义错误消息和响应。

serializer = FormSerializer(data=data)
if not serializer.is_valid(raise_exception=False):
    return Response({"Failure": "Error"}, status=status.HTTP_400_BAD_REQUEST)

是否可以使用raise_exception=True提供的通用响应来填充验证错误?我试图避免使用通用响应,因为如果存在多个错误,它将显示所有验证错误。

响应将类似于

return Response(
     {
          "Failure": "Error", 
          "Error_list": {"field1": "This field is required"}
     },
     status=status.HTTP_400_BAD_REQUEST
) 

3 个答案:

答案 0 :(得分:2)

创建一个 Custom Exception 类,

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


为什么从 PermissionDenied 异常类继承???
看到这样的帖子-Why DRF ValidationError always returns 400

然后在您的序列化程序中,引发异常,如

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


agenameSampleModel类的两个字段


响应将是这样

enter image description here
通过这种方法,
1。。您可以自定义JSON响应
2。。您可以返回任何状态代码
3。。您无需通过True方法传递serializer.is_valid()(不推荐)

答案 1 :(得分:0)

您可以编写自定义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

答案 2 :(得分:0)

一种简单的方法是使用异常消息之一,例如NotFound。参见docs

# views.py
from rest_framework.exceptions import NotFound

class myview(viewsets.ModelViewSet):
    def perform_create(self, serializer):
        raise NotFound("My text here")

这将返回404并将响应更改为您的文本

HTTP 404 Not Found
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
    "detail": "my text here"
}