spring-mvc - Spring MVC for Rest服务,当它是 jackson 反序列化错误时,如何自定义错误 "message"?

标签 spring-mvc jackson spring-boot

我的Spring Boot应用程序中有一个带有单个方法的RestController。此方法处理对/foo url的POST请求。它以一个ID和一个DTO对象为参数。 DTO对象正在由Jackson进行反序列化。我已将@Valid添加到DTO参数以验证正在传递的夫妇属性。我的问题在于,当我为应该为int的字段传递字符串时。这将触发HttpMessageNotReadableException,并且输出的“消息”包含内部对象表示信息,例如类和包名。在@Valid的休眠验证之前,此错误发生在Jackson的反序列化逻辑中的某处。我可以在 Controller 中创建一个@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"
}

如何自定义“消息”字段?

最佳答案

因此,我想出了我认为是解决此Jackson错误并仍然使用Spring的默认rest响应的最佳方法。我不知道您可以将@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());
}

关于spring-mvc - Spring MVC for Rest服务,当它是 jackson 反序列化错误时,如何自定义错误 "message"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29305536/

相关文章:

spring - thymeleaf spring boot templates 子文件夹中的 View

spring-mvc - Spring Bean 配置相当于 <mvc :view-controller path ="..."/>

java - 无法将字符串映射到对象

springSecurityFilterChain 不能为空

java - Apache Commons 配置将属性设置为环境变量 - 如何?

java - SpringBoot @interface 总结不同注解

java - PropertyPlaceholderConfigurer 和 ResourceBundleMessageSource

spring - 从 Spring Boot Controller 返回 JAXB 生成的元素

java - 使用 Jackson ObjectMapper 的 ClassNotFound 异常

java - 在自定义反序列化器中调用默认反序列化器不会影响实例