How to handle the bind exception with @ExceptionHandler
spring, spring-mvc
Solution
import this package
import org.springframework.validation.BindException
not this
import java.net.BindException
Problem
My requirement is to perform the server side validation for the form using Spring 3.0 and Hibernate Validator.Remember that I am submitting the form using AJAX call.My Controller class code is like below. ``` public ModelAndView generatePdfReport(@ModelAttribute("reports") @Valid ReportsCommand model, BindingResult result, ModelAndView modelAndView, HttpServletRequest request, HttpServletResponse response) throws Exception { if (result.hasErrors()) { throw new BindException(result); } else{ ... } ``` update... ``` @ExceptionHandler(BindException.class) public @ResponseBody String handleException(BindException e,HttpServletRequest request, HttpServletResponse response) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return e.getMessage(); } ``` This is the Handler Method I placed in the controller.I used the @ResponseBody annotation but still it is showing the response in html format not in JSON format... What is the wrong in my code.. And the below is the field I am validating ``` @Size(min = 2, max = 3, message = "calltype must between 2 to 3 Characters.") private String callType; ``` If I give size as more than three, it is entering into the if and throwing the exception.What I want is that, I want to handle this exception and return the json response.May be I can do this using @ExceptionHandler but don't know how.Or any other solution to resolve this problem also will be greatly appreciated.