【问题标题】:Spring MVC jackson exception handlingSpring MVC杰克逊异常处理
【发布时间】:2015-01-24 07:50:23
【问题描述】:

我可以为 @RequestBody 参数处理 Jackson UnrecognizedPropertyException 吗?我该如何配置?

我正在开发一个 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();
    }       
}

我的控制器:

@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 字符串。我怎样才能做到这一点?

【问题讨论】:

    标签: json spring spring-mvc


    【解决方案1】:

    使用@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
      }
    }
    

    【讨论】:

    • 并且可以使用@ControllerAdvice 注册一个全局异常处理程序,如本文所述:journaldev.com/2651/…
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 2017-07-01
    • 1970-01-01
    相关资源
    最近更新 更多