Mapping DTO to Entity with ModelMapper including exceptions

Viewed 1236

I am having a DTO (OpeningHoursPeriodDTO) and an Entity (OpeningHoursPeriod), which I want to map using ModelMapper. As long I throw no exception inside the converter method all is working fine as expected.

Here the code of the converter:

modelMapper
        .createTypeMap(OpeningHoursPeriodDTO.class, OpeningHoursPeriod.class)
        .setConverter(converter -> {
            OpeningHoursPeriodDTO openingHoursPeriodDTO = converter.getSource();
            if (openingHoursPeriodDTO == null) {
                return null;
            }

            if (openingHoursPeriodDTO.getOpen() == null || openingHoursPeriodDTO.getClose() == null) {
                throw new BadRequestException("Opening hours and closing hours must be present");
            }

            if (!Objects.equals(
                    openingHoursPeriodDTO.getOpen().getDay(),
                    openingHoursPeriodDTO.getClose().getDay())) {
                throw new BadRequestException("Opening and close day for a period must be for the same day");
            }

            return OpeningHoursPeriod.builder()
                    .id(openingHoursPeriodDTO.getId())
                    .day(openingHoursPeriodDTO.getOpen().getDay())
                    .openTime(LocalTime.parse(openingHoursPeriodDTO.getOpen().getTime(), TIME_FORMATTER))
                    .closeTime(LocalTime.parse(openingHoursPeriodDTO.getClose().getTime(), TIME_FORMATTER))
                    .build();
        });

The problem is that if it happens to throw an Exception, I get a 500 Status Code in my Spring Boot application, although the status code of the BadRequestException should be 400. Any Idea how to best handle such converter exceptions?

1 Answers

You could add @ResponseStatus to your exception:

@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
}

This will generate a 400 when this exception is thrown.

But there are various other options to handle exceptions in REST Controllers. Have a look here:

https://www.baeldung.com/exception-handling-for-rest-with-spring

Related