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?