Data Binding Error Handling in Spring MVC

user1166031 picture user1166031 · Jul 31, 2012 · Viewed 7.8k times · Source

I have a question about data binding in Spring MVC.

I have a Controller which accepts a JSON request in the form of @RequestBody. I have all the JSR 303 validations in place and it works like a charm.

  • JSON Request

    public class TestJSONRequest {
    
        @Size(min=10,message="{invalid.demo.size}")
        String demo;
    
        int code;
    }
    
  • Controller

    @Controller
    @RequestMapping("/test")
    public class TestController {
    
        public void testEntry(@RequestBody TestJSONRequest jsonRequest,ModelMap map)
    
          Set<ConstraintViolation<TestJSONRequest>> violationList = validator.val(jsonRequest);
          ....
          ....
          TestJSONResponse response = // Do complex Logic.
          modelMap.addattribute("TestJSONResponse",response);
        }
    }
    

But JSR 303 validations kick in once the incoming JSON data is bound to the Request object.

If I send ab in the code field of the input JSON request, binding would itself fail.

How do I handle that?

I want to catch those data binding errors and do some kind of generalized error handling in my controller.

Could you please help me out on this?

P.S - I am using Spring 3.0.3

Answer

Muel picture Muel · Jul 31, 2012

According to the current Spring documentation (V3.1) :

Unlike @ModelAttribute parameters, for which a BindingResult can be used to examine the errors, @RequestBody validation errors always result in a MethodArgumentNotValidException being raised. The exception is handled in the DefaultHandlerExceptionResolver, which sends a 400 error back to the client.

Now you can to tell Spring that you'd like to handle this, by creating a new method, as follows:

@ExceptionHandler(MethodArgumentNotValidException.class)
public String handleValidation(MethodArgumentNotValidException e, ModelMap map) {
    List<ObjectError> errors = e.getBindingResult() .getAllErrors();
    // your code here...
    return "path/to/your/view";
}

Finally, have a read of the Spring docs wrt @ExceptionHandler. There's most likely some useful information there.