使用Spring MVC开发Rest服务时,当出现Jackson反序列化错误时,如何自定义错误信息"message"?

9

我的Spring Boot应用程序中有一个RestController,其中包含一个方法。该方法处理对/foo url的POST请求。它接受ID和DTO对象作为参数。DTO对象由Jackson反序列化。我已经在DTO参数中添加了@Valid以验证传递的属性。当我传递字符串到一个应该是整数字段的字段时,就会触发HttpMessageNotReadableException,输出的"message"包含类和包名等内部对象表示信息。这个错误发生在Jackson反序列化逻辑之前,在@Valid的Hibernate验证之前。我可以在控制器中创建一个@ExceptionHandler注释的方法来处理这些类型的异常,但我必须手动构建json输出或使用Jackson的Spring默认消息。

当出现此异常时,这是Spring输出的内容:

{
"timestamp": 1427473174263,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "Could not read JSON: Can not construct instance of int from String value 'SHOULDNT BE A STRING': not a valid Integer value\ at [Source: java.io.PushbackInputStream@34070211; line: 1, column: 3] (through reference chain: com.blah.foo.dto.CustomerProductPromotionDTO[\"productId\"]); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of int from String value 'SHOULDNT BE A STRING': not a valid Integer value\ at [Source: java.io.PushbackInputStream@34070211; line: 1, column: 3] (through reference chain: com.blah.foo.dto.CustomerProductPromotionDTO[\"productId\"])",
"path": "/customers/123456/promotions"
}

我该如何自定义那个“消息”字段?

3个回答

3

我想到了一个解决Jackson错误并仍然使用Spring默认rest响应的最佳方法。我没有意识到你可以在这些非自定义异常类型中与@ResponseStatus一起使用@ExceptionHandler。

 */
@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="There was an error processing the request body.")
public void handleMessageNotReadableException(HttpServletRequest request, HttpMessageNotReadableException exception) {
    LOGGER.error("\nUnable to bind post data sent to: " + request.getRequestURI() + "\nCaught Exception:\n" + exception.getMessage());
}

0

0
在你的控制器(Controller)中,你可以添加一个方法来自定义错误响应:
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<?> handleMessageNotReadableException(
            HttpServletRequest request, 
            HttpMessageNotReadableException e) {

    //Build your response and send it back
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接