Enums in serializer error message

i faced something weird
this is my serializer. as you can see i used enums in error message. when i enter invalid phone number a message like this is shown: “A server error occurred. Please contact the administrator.”

class PhoneSerializer(serializers.Serializer):
    phone = serializers.RegexField(
        regex=REGEX,
        error_messages={
            "invalid": FaultCode.INVALID_PHONE_NUMBER_PATTERN.value
        },
    )

Can you share the code of your FaultCode class to better understand the problem?

class FaultCode(Enum):
    SMS_PROVIDER_FAILURE = 0
    INVALID_PHONE_NUMBER_PATTERN = 22

The problem you are experiencing is due to the way the Django REST Framework (DRF) handles the error_messages dictionary and the Enum class. The value attribute of the Enum class returns an integer and DRF expects a string in the error_messages dictionary.

To solve this problem, you can convert the enum value to a string in the error_messages dictionary, I guess this will solve the problem.

class PhoneSerializer(serializers.Serializer):
    phone = serializers.RegexField(
        regex=REGEX,
        error_messages={
            "invalid": str(FaultCode.INVALID_PHONE_NUMBER_PATTERN.value)
        },
    )

class FaultCode(Enum):
    SMS_PROVIDER_FAILURE = 0
    INVALID_PHONE_NUMBER_PATTERN = 22

You can also try this. More descriptive messages might be good for the project

class FaultCode(Enum):
    SMS_PROVIDER_FAILURE = "SMS provider failure"
    INVALID_PHONE_NUMBER_PATTERN = "Invalid phone number pattern"

class PhoneSerializer(serializers.Serializer):
    phone = serializers.RegexField(
        regex=REGEX,
        error_messages={
            "invalid": FaultCode.INVALID_PHONE_NUMBER_PATTERN.value
        },
    )

1 Like