The org.springframework.web.servlet.view.ContentNegotiatingViewResolver let's you map a response from your controller and have it auto formatted without a nary of hint in the actual code. However, exception handling of the controller does not seem to follow this ideology. Maybe this will be fixed in a future version (I hope) or is already fixed in a newer version (don't feel like upgrading libs atm). For context, I'm using Spring 3.0.5-Release.
Here is how my exception handler should look and act.
@ExceptionHandler(KnownException.class)
public SessionResponse handleException(KnownException e, HttpServletRequest request) {
SessionResponse response = new SessionResponse();
response.errorCode = e.code;
return response;
}
SessionResponse is just a POJO, nothing special. However, Spring doesn't like this approach and says that it can not find a ContentNegotiatingBlahBlah...
To make it work, you can do the following...
@ExceptionHandler(KnownException.class)
public ModelAndView handleException(KnownException e, HttpServletRequest request) {
SessionResponse response = new SessionResponse();
response.errorCode = e.code;
return new ModelAndView("", "error", response);
}
For whatever reason, wrapping it in a ModelAndView object will trigger spring to render the output correctly. Which, in my case is JSON or XML based on the suffix used for the request.
Maybe this will help someone else. Googling only turns up forum posts with no answers.
References:
http://forum.springsource.org/archive/index.php/t-82802.html