如何在ModelMapper转换器中保留异常消息

时间:2018-09-18 11:52:21

标签: java spring-boot modelmapper

我正在使用ModelMapper,在那里我定义了一些PostConverters,例如:

    modelMapper
            .createTypeMap(TestDTO.class, Test.class)
            .setPostConverter(converter -> {
                Test dest = converter.getDestination();
                TestDTO source = converter.getSource();
                if (source.getDependency() != null) {
                    Dependency dependency = dependencyRepository
                            .findById(source.getDependency().getId())
                            .orElseThrow(() -> new BadRequestException("Invalid Dependency"));
                    dest.setDependency(dependency);
                }
                return dest;
            });

该代码的问题在于,如果我为依赖项放置了无效的ID,那么我将收到如下响应负载:

{
    "timestamp": "2018-09-18T13:51:05.203+0200",
    "status": 400,
    "error": "Bad Request",
    "message": "ModelMapper mapping errors:\n\n1) Converter ....",
    "path": "/api/test"
}

但是我希望在错误消息中得到Invalid Dependency。知道怎么做吗?

这是BadRequestException的定义:

@ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RunTimeException {

    public BadRequestException() {
        super("Bad Request");
    }

    public BadRequestException(String message) {
        super(message);
    }

    public BadRequestException(String pattern, Object... parameters) {
        super(pattern, parameters);
    }
}

1 个答案:

答案 0 :(得分:0)

错误似乎出在带有注释的异常处理中,请参见此处:
https://docs.spring.io/spring/docs/4.2.4.RELEASE/javadoc-api/org/springframework/web/bind/annotation/ResponseStatus.html

它说:
“警告:在异常类上使用此批注时,或在设置此批注的原因属性时,将使用HttpServletResponse.sendError方法。” 似乎该方法默认情况下不使用您的异常消息。 因此,您可以尝试定义“硬编码”消息并使用

给出具体字符串
 @ResponseStatus(value = HttpStatus.BadRequest, reason = "Invalid Dependency")

或者以这种方式进行:

public class BadRequestException extends RunTimeException {

public BadRequestException() {
    super("Bad Request");
}

public BadRequestException(String message) {
    super(message);
}

public BadRequestException(String pattern, Object... parameters) {
    super(pattern, parameters);
}

}

@ControllerAdvice
public class CustomExceptionResolver {

    @ExceptionHandler(BadRequestException.class)
    public ResponseEntity<Error> resolveAndSendException(BadRequestException e) throws IOException {
        return new ResponseEntity<Error>(e, HttpStatus.BadRequest); 
    }
}

我希望第一个略有更改:
引入一个名为InvalidDependencyException的新类,并将第一个示例应用到该类,这样您就可以收到消息,并且仍然可以将集成消息用于任何其他错误请求。 (当然,将它扔到您的流部分中)