Custom exception for org.mapstruct.ValueMappings method

17 Views Asked by At

In a Mapstruct environment, I have a method taking a String and returning an Enum value. As the String can be out of the list of the Enum, the ValueMappings method can be configured to throw an IllegalArgumentException

@ValueMappings({
        @ValueMapping(source = "ACTIVE", target = "A"),
        @ValueMapping(source = "INACTIVE", target = "I"),
        @ValueMapping(source = MappingConstants.ANY_REMAINING, target = MappingConstants.THROW_EXCEPTION)
    })
String statusEnumToString(Status status);

Is there a way to throw a CustomArgumentException instead of an IllegalArgumentException?

1

There are 1 best solutions below

0
Filip On

You can use EnumMapping#unexpectedValueMappingException to customize the exception that should be thrown.

e.g.

@ValueMappings({
        @ValueMapping(source = "ACTIVE", target = "A"),
        @ValueMapping(source = "INACTIVE", target = "I"),
        @ValueMapping(source = MappingConstants.ANY_REMAINING, target = MappingConstants.THROW_EXCEPTION)
    })
@EnumMapping(unexpectedValueMappingException = CustomArgumentException.class)
String statusEnumToString(Status status)

You can read more about it in the EnumMapping#unexpectedValueMappingException Javadoc