Spring MVC exception handling jackson

Is it possible to handle Jackson UnrecognizedPropertyExceptionfor a parameter @RequestBody? How can I customize this?

I am working on a spring MVC project and I am using jackson as a json plugin. Any misuse of the field name in the json request will result in an error page, which should be a json string consisting of an error message. I'm new to spring, and I think that this error handling can be done with some spring configuration, but failed after several attempts. Any help?

Here is my mvc configure:

@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {     
    @Bean
    public ViewResolver resolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        return bean;
    }    
    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }       
}

My controller:

@RequestMapping(value = "/Login", method = RequestMethod.POST, 
    consumes="application/json", produces = "application/json")
public @ResponseBody AjaxResponse login(
    @RequestBody UserVO user, HttpServletRequest request) {
    //do something ...
}

Normal json request:

{"Username":"123123", "Password":"s3cret"}

But if I send the following request:

{"Username":"123123", "pwd":"s3cret"}

, spring UnrecognizedPropertyException , json. ?

+4
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
  }
}
+3

All Articles