我有一个 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/