3
votes

I have a following problem. I have a model level validation which checks data consistency on each save. In serializers, if this model level validation works, it produces server error 500 with trace-back, whereas serializer.Validationerror in serializer produces nice and clean 400 error with error message in json.

In order to convert model level Validationerror to serializers. Validationerror I use following code in my serializers.

def perform_create(self, validated_data):
    try:
        return super().perform_create(validated_data)
    except exceptions.ValidationError as err:
        raise serializers.ValidationError(
            f'Model level validation assertion -- {str(err)}'
        ) from err

It works, but I cant and don’t want to override each and every one serializer to convert Validationerror to serializers. Validationerror.

Question is - is it any way to catch all Validationerror and convert them to serializers. Validationerrors?

1

1 Answers

3
votes
from rest_framework.views import exception_handler
from rest_framework.response import Response as DRF_response
from rest_framework import status

from django.core import exceptions
from django.views import View
from django.http import response


def custom_exception_handler(exc: Exception, context: View) -> [response, None]:

    response = exception_handler(exc, context)

    if isinstance(exc, exceptions.ValidationError):
        data = exc.message_dict
        return DRF_response(data=data, status=status.HTTP_400_BAD_REQUEST, )

    return response

I made a custom error handler which catches all Django standard Validation errors and return DRF style reponse on them.