返回JSON或XML的ExceptionHandler在Spring MVC 3中不起作用
问题内容:
代码是这样的:
@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;
}
}
当我尝试curl -H“ Accept:application / json” -v“
http://localhost.com:8080/testerror”时,出现以下错误:org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver-
找不到支持返回类型[class com.kibboko.poprocks.appservices.dtos.ErrorTO]和[application /
json]的HttpMessageConverter
但是,如果我尝试curl -H“ Accept:application / json” -v“
http://localhost.com:8080/test”,则可以工作并返回json响应。“ application / xml”也起作用。
我需要照顾的异常处理程序有什么特别之处,以便它可以与json或xml一起使用吗?谢谢!
问题答案: