【发布时间】:2015-06-01 01:37:21
【问题描述】:
我的 Spring Boot 应用程序中有一个带有单一方法的 RestController。此方法处理对 /foo url 的 POST 请求。它接受一个 ID 和一个 DTO 对象作为参数。 Jackson 正在反序列化 DTO 对象。我已将 @Valid 添加到 DTO 参数以验证正在传递的几个属性。我的问题在于当我为一个应该是 int 的字段传入一个字符串时。这会触发 HttpMessageNotReadableException 并且输出的“消息”包含内部对象表示信息,例如类和包名称。在对@Valid 进行休眠验证之前,此错误发生在某个地方的 Jackson 反序列化逻辑中。我可以在我的控制器中创建一个 @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"
}
如何自定义“消息”字段?
【问题讨论】:
标签: spring-mvc jackson spring-boot