使用ModelMapper将DTO映射到实体,包括异常

时间:2018-09-20 07:17:12

标签: java spring-boot modelmapper

我有一个DTO(OpeningHoursPeriodDTO)和一个实体(OpeningHoursPeriod),我想使用ModelMapper进行映射。 只要我在转换器方法内没有引发任何异常,一切就可以按预期工作。

以下是转换器的代码:

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();
        });

问题是,即使BadRequestException的状态码应该是400,如果碰巧抛出了异常,我在Spring Boot应用程序中也会得到500状态码。 知道如何最好地处理此类转换器异常吗?

1 个答案:

答案 0 :(得分:0)

您可以将@ResponseStatus添加到您的例外中:

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

抛出此异常时,将生成400。

但是还有其他各种选项可以处理REST控制器中的异常。在这里看看:

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