Automate JackSON conversion in ExceptionHandler?
Hi,
I am writing a RESTful web service. All the outputs of the web service is currently in JSON format and I make use of MappingJacksonHttpMessageConverter to convert all my positive output to JSON.
I facing some problems on the error handling part. As I read from internet, @ExceptionHandler only can returns String / MAV. I could not apply the @ResponseBody that I used in other method to auto-convert my output to JSON. My snapshot of code as below (modified from Spring Doc v3.0.0, Section 18.2.6):
Code:
@Controller
public class SimpleController {
// other controller method omitted
@ExceptionHandler(IOException.class)
public String handleIOException(IOException ex, HttpServletRequest request) {
// Convert 'ex.getMessage()' with to ErrorMessage with Object Mapper
ErrorMessage errorMessage = new ErrorMessage(ex.getMessage());
String ret = mapper.writeValueAsString(errorMessage);
....
return ret;
}
Code:
@XmlRootElement(name="errorMessage")
public class ErrorMessage {
private String error_message;
public ErrorMessage() {}
public ErrorMessage(String error_message) {
this.error_message = error_message;
}
public String getError_message() {
return error_message;
}
public void setError_message(String error_message) {
this.error_message = error_message;
}
}
The expecting output is (in JSON)
{"error_message":"this is the real exception error message."}
My questions is - is that any idea to automate the process besides doing to conversion in every @ExceptionHandler method?
Thanks for your advises.