Kev*_*n M 7 spring-mvc jackson spring-boot
我的Spring Boot应用程序中有一个带有单个方法的RestController.此方法处理对/ foo url的POST请求.它将ID和DTO对象作为参数.DTO对象正在被杰克逊反序列化.我已将@Valid添加到DTO参数以验证传递的两个属性.我的问题在于我为一个应该是int的字段传入一个String.这会触发HttpMessageNotReadableException,输出的"message"包含类和类名称等内部对象表示信息.在@Valid的hibernate验证之前,杰克逊反序列化逻辑中发生了这个错误.我可以在我的控制器中创建一个@ExceptionHandler注释方法来处理这些类型的异常,但是我必须手动制作json输出或者坚持使用Spring从Jackson使用的默认消息.
这是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"
}
Run Code Online (Sandbox Code Playgroud)
如何自定义"消息"字段?
所以我想出了我认为解决 Jackson 错误的最佳方法,并且仍然使用 Spring 的默认休息响应。我没有意识到您可以将 @ExceptionHandler 与 @ResponseStatus 结合使用来处理这些非自定义异常类型。
*/
@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());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1960 次 |
| 最近记录: |