问题
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!
回答1:
Seems like a known Spring bug (Fixed in 3.1 M1)
https://jira.springsource.org/browse/SPR-6902
回答2:
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;
}
...
}
来源:https://stackoverflow.com/questions/4948627/exceptionhandler-returning-json-or-xml-not-working-in-spring-mvc-3