MappingConstants.THROW_EXCEPTION example

In this post under MapStruct, I will explain with example the purpose of enum “MappingConstants.THROW_EXCEPTION”.

This enum is mainly used when mapping source enum constant to destination enum constant.

If you want to throw an exception for some source enum constant. We can use this enum constant.

Below is the example showing the usage.

Lets say we have the below source enum

Source enum

package package14;

public enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY;
}

We have to map it to below destination enum

Destination enum

package package14;

public enum Week {
    WEEK_DAY
}

As you can see, we can map “MONDAY”, “TUESDAY”, “WEDNESDAY”, “THURSDAY”, and “FRIDAY” to “WEEK_DAY” but we cannot map “SATURDAY” and “SUNDAY” as there is no corresponding enum constant available.

In that case we can throw an exception.

We can instruct MapStruct to throw an exception using the enum constant “MappingConstants.THROW_EXCEPTION” as shown in the below mapper interface

Mapper interface

package package14;

import org.mapstruct.Mapper;
import org.mapstruct.MappingConstants;
import org.mapstruct.ValueMapping;
import org.mapstruct.ValueMappings;

@Mapper
public interface DayToWeekMapper {
    @ValueMappings({
            @ValueMapping(source = "MONDAY", target = "WEEK_DAY"),
            @ValueMapping(source = "TUESDAY", target = "WEEK_DAY"),
            @ValueMapping(source = "WEDNESDAY", target = "WEEK_DAY"),
            @ValueMapping(source = "THURSDAY", target = "WEEK_DAY"),
            @ValueMapping(source = "FRIDAY", target = "WEEK_DAY"),
            @ValueMapping(source = MappingConstants.ANY_UNMAPPED, target = MappingConstants.THROW_EXCEPTION)
    })
    Week dayToWeekMapping(Day day);
}

In the above code, at line 16, I am telling MapStruct that for any unmapped source enum constant (in this case it is “SATURDAY” and “SUNDAY”) throw an exception.

In this case, we haven’t mapped constant “SATURDAY” and “SUNDAY” from source enum. As a result whenever MapStruct encounter any one of these two source enum constant it will throw an exception.

Below is the main class for your reference.

Main class

package package14;

import org.mapstruct.factory.Mappers;

public class Example14 {
    public static void main(String[] args) {
        DayToWeekMapper dayToWeekMapper = Mappers.getMapper(DayToWeekMapper.class);

        Week week = dayToWeekMapper.dayToWeekMapping(Day.MONDAY);
        System.out.println(week);
        week = dayToWeekMapper.dayToWeekMapping(Day.SUNDAY);
        System.out.println(week);
    }
}

Below is the output

Output

WEEK_DAY
Exception in thread "main" java.lang.IllegalArgumentException: Unexpected enum constant: SUNDAY
    at MapStructConcepts.main/package14.DayToWeekMapperImpl.dayToWeekMapping(DayToWeekMapperImpl.java:31)
    at MapStructConcepts.main/package14.Example14.main(Example14.java:11)

Leave a comment