spring - RequestMapping转换异常

标签 spring spring-mvc

我有一个 Spring RequestMapping,它采用 JSON 结构并将其转换为 POJO。如果我向路由发送格式错误的 JSON 结构,我会收到“400 错误请求”,但我希望收到一条错误消息,说明为什么这是错误请求。我有一个验证器也检查 JSON 结构,但如果结构无法转换,它似乎不会被调用。有没有办法可以访问内置的 HttpMessageConverter 错误或异常?

最佳答案

我认为你可以使用ResponseEntityExceptionHandler为此,通过重写 handleHttpMessageNotReadable 方法。

来自:17.11.3 Handling Standard Spring MVC Exceptions :

If you prefer to write error content via @ExceptionHandler methods you can extend ResponseEntityExceptionHandler instead. This is a convenient base for @ControllerAdvice classes providing an @ExceptionHandler method to handle standard Spring MVC exceptions and return ResponseEntity. That allows you to customize the response and write error content with message converters. See the ResponseEntityExceptionHandler javadocs for more details.

可以在此处找到 ResponseEntityExceptionHandler 的示例用法:http://www.jayway.com/2013/02/03/improve-your-spring-rest-api-part-iii/

否则你可以在这里找到更多 spring mvc 异常处理方法: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

如果您的需求不太复杂,您可能只想使用 SimpleMappingExceptionResolver

关于spring - RequestMapping转换异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29808899/

相关文章:

java - 我应该避免在 Spring util 包中使用类吗?

java - Hibernate JSR303 验证和错误生成的 propertyPath

java - 在服务器运行时将表内容从 Oracle DB 加载到 Spring Bean

java - 初学者 hibernate/spring/hibernate-search 问题(配置)

java - 身份验证过滤器不适用于 Spring Boot

java - 如何将盐传递给 Spring?

java - 是否有@RunAs 的 Spring 模拟?

java - 如何在方法之间保存数据

spring - Spring MVC 3.1 中的 Flash 属性对重定向 JSP 不可见

java - Java 导入语句错误 "The import javax.validation.constraints.NotNull cannot be resolved"