Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC jackson exception handling

Can I handle Jackson UnrecognizedPropertyException for a @RequestBody parameter? How can I configure this?

I'm working on a spring MVC project, and I use jackson as json plugin. Any mis-spell of the field name in a json request will lead to a error page, which should be a json string consist of error message. I'm a newbie to spring, and I think 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 request json is:

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

But if I send the following request:

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

which field name is mis-spell, then Spring catch this UnrecognizedPropertyException, and returned a error page, but I want to catch this exception and return a json string. How can I achieve this?

like image 468
zhaodaolimeng Avatar asked Sep 29 '22 08:09

zhaodaolimeng


1 Answers

Use @ExceptionHandler annotation. Some documentation about it: 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
  }
}
like image 181
Ilya Ovesnov Avatar answered Nov 15 '22 08:11

Ilya Ovesnov