我可以处理 jackson 吗UnrecognizedPropertyException
对于 @RequestBody
范围?我该如何配置?
我正在做一个 spring MVC 项目,我使用 jackson 作为 json 插件。 json 请求中字段名称的任何拼写错误都会导致错误页面,该页面应该是由错误消息组成的 json 字符串。我是 spring 的新手,我认为这个错误处理可以通过一些 spring 配置来完成,但在多次尝试后失败了。有什么帮助吗?
这是我的 mvc 配置:
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver resolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
return bean;
}
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
我的 Controller :
@RequestMapping(value = "/Login", method = RequestMethod.POST,
consumes="application/json", produces = "application/json")
public @ResponseBody AjaxResponse login(
@RequestBody UserVO user, HttpServletRequest request) {
//do something ...
}
正常请求json是:
{"Username":"123123", "Password":"s3cret"}
但是如果我发送以下请求:
{"Username":"123123", "pwd":"s3cret"}
哪个字段名称拼写错误,那么 Spring 会捕获这个
UnrecognizedPropertyException
,并返回一个错误页面,但我想捕获此异常并返回一个 json 字符串。我怎样才能做到这一点?
最佳答案
使用@ExceptionHandler 注释。关于它的一些文档:http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
@Controller
public class WebMvcConfig {
@RequestMapping(value = "/Login", method = RequestMethod.POST,
consumes="application/json", produces = "application/json")
public @ResponseBody AjaxResponse login(@RequestBody UserVO user, HttpServletRequest request) {
//do something ...
}
@ExceptionHandler(UnrecognizedPropertyException.class)
public void errorHandler() {
// do something. e.g. customize error response
}
}
关于json - Spring MVC jackson 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27141454/