如何在Django Rest框架中显示自定义错误消息

时间:2019-07-18 10:22:57

标签: django django-rest-framework error-messaging

我正在尝试创建类别,同时创建类别时,我想显示类似“类别创建”的消息,或者如果它无法创建类别,我想为此显示一些错误消息以及状态代码。该代码仅显示状态代码,但是如何抛出错误消息以及状态代码?

serializers.py

class CategorySerializer(serializers. HyperlinkedModelSerializer):   
    name = serializers.CharField(
            required=True,
            validators=[UniqueValidator(queryset=Category.objects.all())]
            ) 
    class Meta:        
        model = Category        
        fields = (
            'id', 
            'name', 
            'description',
            'parent_id',
            'start',
            'end',
            'is_service',
            'display_home',
            'is_achievement_option',
        )   
        read_only_fields = ('id',)

views.py

@api_view(['POST'])
@authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication))
@permission_classes((permissions.IsAdminUser,))
def add(request):
    if request.method == 'POST':
        serializer = CategorySerializer(data = request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

1 个答案:

答案 0 :(得分:0)

  1. 使用try...except
@api_view(['POST'])
@authentication_classes((SessionAuthentication, BasicAuthentication, TokenAuthentication))
@permission_classes((permissions.IsAdminUser,))
def add(request):
   try: 
    if request.method == 'POST':
        serializer = CategorySerializer(data = request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:
        return Response({'status': 500, 'error': str(e)})

  1. 使用自定义异常处理程序

    自定义例外

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['status_code'] = response.status_code
    # ... write your logic here ...
    # response.data['message'] = str(exc)

    return response

settings.py

REST_FRAMEWORK = {
    # ... 
    'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler'
    # ...
}