code is like this:
@Controller
public class TestController {
@RequestMapping(value = "/testerror", method = RequestMethod.GET)
public @ResponseBody ErrorTO testerror(HttpServletRequest request,HttpServletResponse response) {
throw new ABCException("serious error!");
}
@ExceptionHandler(ABCException.class)
public @ResponseBody ErrorTO handleException(ABCException ex,
HttpServletRequest request, HttpServletResponse response) {
response.setStatus(response.SC_BAD_REQUEST);
return new ErrorTO(ex.getMessage());
}
@RequestMapping(value = "/test", method = RequestMethod.GET)
public @ResponseBody ErrorTO test(HttpServletRequest request,
HttpServletResponse response) {
ErrorTO error = new ErrorTO();
error.setCode(-12345);
error.setMessage("this is a test error.");
return error;
}
}
when I tried curl -H "Accept:application/json" -v "http://localhost.com:8080/testerror" I got this error: org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver - Could not find HttpMessageConverter that supports return type [class com.kibboko.poprocks.appservices.dtos.ErrorTO] and [application/json]
but if I try curl -H "Accept:application/json" -v "http://localhost.com:8080/test", worked and returned json response. "application/xml" worked too.
Is there anything special about exception handler I need to take care of so it can work with json or xml? Thanks!
It appears that AnnotationMethodHandlerExceptionResolver
has its own array of HttpMessageConverter
s. You need to configure it to use the same array as used by AnnotationMethodHandlerAdapter
.
However, it can be complicated when AnnotationMethodHandlerAdapter
is declared implicitly. Perhaps declaring the following FactoryBean
may help in all cases:
public class AnnotationMethodHandlerExceptionResolverFactoryBean
implements FactoryBean<AnnotationMethodHandlerExceptionResolver> {
@Autowired
private AnnotationMethodHandlerAdapter a;
public AnnotationMethodHandlerExceptionResolver getObject()
throws Exception {
AnnotationMethodHandlerExceptionResolver r = new AnnotationMethodHandlerExceptionResolver();
r.setMessageConverters(a.getMessageConverters());
return r;
}
...
}
Seems like a known Spring bug (Fixed in 3.1 M1)
https://jira.springsource.org/browse/SPR-6902
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With