How to configure MapStruct to throw an exception when enum values can't be mapped

Viewed 3161

This is my Mapper:

@Mapper
public interface ProductMapper {
    ProductClassification toProductClassification(ProductTypes pisType);
}

Where ProductTypes and ProductClassification are enums. I want it to throw an exception when it can't map the enums, but I get compiler error: The following constants from the source enum have no corresponding constant in the target enum and must be be mapped via adding additional mappings: EXTERNAL, UNKNOWN.

I tried with @ValueMappings annotation, but can only configure it to set the value to null, which is not sufficient:

@ValueMappings({
    @ValueMapping(source = MappingConstants.ANY_REMAINING, target = MappingConstants.NULL)
})

What would be the right way to configure MapStruct mapper to throw an exception when it can't map enum constants?

1 Answers

This is currently not possible.

However, this feature will be part of the next 1.5 release. It is already implemented and available in the SNAPSHOT builds.

There will be a new mapping constant accessible via MappingConstants.THROW_EXCEPTION and you can set it to a ValueMappingTarget.

So in this example in order to throw an exception for any remaining mapping you can write:

@ValueMapping(source = MappingConstants.ANY_REMAINING, target = MappingConstants.THROW_EXCEPTION)

Note at the time of answering this question (29.03.2021) this feature is not yet released.

Related