【发布时间】:2011-07-03 02:23:11
【问题描述】:
我尝试为休息控制器配置一个弹簧异常处理程序,该处理程序能够根据传入的接受标头将映射呈现到 xml 和 json。它现在抛出一个 500 servlet 异常。
这行得通,它拿起了 home.jsp:
@ExceptionHandler(IllegalArgumentException.class)
public String handleException(final Exception e, final HttpServletRequest request, Writer writer)
{
return "home";
}
这不起作用:
@ExceptionHandler(IllegalArgumentException.class)
public @ResponseBody Map<String, Object> handleException(final Exception e, final HttpServletRequest request, Writer writer)
{
final Map<String, Object> map = new HashMap<String, Object>();
map.put("errorCode", 1234);
map.put("errorMessage", "Some error message");
return map;
}
在同一控制器中,通过相应的转换器将响应映射到 xml 或 json:
@RequestMapping(method = RequestMethod.GET, value = "/book/{id}", headers = "Accept=application/json,application/xml")
public @ResponseBody
Book getBook(@PathVariable final String id)
{
logger.warn("id=" + id);
return new Book("12345", new Date(), "Sven Haiges");
}
【问题讨论】:
标签: rest spring-mvc