In a Controller class I can do the following for ajax calls:
Code:
@ExceptionHandler(Exception.class)
public @ResponseBody void handleException(Exception ex, HttpServletRequest request) {
// Build a JSON representation of the exception.
String response = jsonUtil.getExceptionJson(ex);
// Write JSON response to the response object
}
@RequestMapping(value = "/doAjax", method = RequestMethod.POST)
public @ResponseBody Map<String,String> doAjax(params omitted) {
Map<String, String> map = new HashMap<String, String>();
// Do business methods which can throw exceptions and build map.
return map;
}
or the following for non ajax.
Code:
@ExceptionHandler(Exception.class)
public String handleException(Exception ex, HttpServletRequest request) {
return "exceptionView";
}
@RequestMapping(value = "/doNonAjax", method = RequestMethod.POST)
public String doNonAjax(params omitted) {
// Show completed view
// Do business methods which can throw exceptions and add to model.
return "completedView";
}
However as the ExceptionHandler method is applied to a full class then you can not mix and match ajax and non ajax methods as the exception handler either needs to either return a view OR a response body.
To get around this I need to do the following with a mixed class:
Code:
@ExceptionHandler(Exception.class)
public String handleException(Exception ex, HttpServletRequest request) {
return "exceptionView";
}
@RequestMapping(value = "/doAjax", method = RequestMethod.POST)
public @ResponseBody Map<String,String> doAjax(params omitted) {
try {
Map<String, String> map = new HashMap<String, String>();
// Do business methods which can throw exceptions and build map.
return map;
}
catch(Exception e) {
String exceptionJson = jsonUtil.getExceptionJson(ex);
// Add exceptionJson to the response map.
}
}
@RequestMapping(value = "/doNonAjax", method = RequestMethod.POST)
public String doNonAjax(params omitted) {
// Show completed view
// Do business methods which can throw exceptions and add to model.
return "completedView";
}
That is a crude example to show what I mean. What I am getting at is it seems a functional downfall that a Single method can not have its own ExceptionHandler set like.
@RequestMapping(value = "/doNonAjax", method = RequestMethod.POST, exceptionHandler = "someHandler")
public String doNonAjax(params omitted)
@RequestMapping(value = "/doAjax", method = RequestMethod.POST, exceptionHandler = "someOtherHandler")
public @ResponseBody Map<String, String> doAjax(params omitted)
Chris