Spring @ExceptionHandler不适用于@ResponseBody
问题内容:
我尝试为rest控制器配置一个spring异常处理程序,该控制器能够根据传入的accept标头将一个映射同时映射到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");
}
任何人?
问题答案:
你的方法
@ExceptionHandler(IllegalArgumentException.class)
public @ResponseBody Map<String, Object> handleException(final Exception e, final HttpServletRequest request, Writer writer)
不起作用,因为它的返回类型错误。@ExceptionHandler方法只有两种有效的返回类型:
- 串
- ModelAndView。
有关更多信息,请参见http://static.springsource.org/spring/docs/3.0.x/spring-framework-
reference/html/mvc.html
。这是链接中的特定文本:
返回类型可以是String,它被解释为视图名称或ModelAndView对象。
回应评论
Thanx,看来我太过分了。不好。有什么主意如何以xml / json格式自动提供异常?– Sven Haiges 7小时前
这是我所做的事情(我实际上是在Scala中完成的,因此我不确定语法是否完全正确,但是您应该明白要点)。
@ExceptionHandler(Throwable.class)
@ResponseBody
public void handleException(final Exception e, final HttpServletRequest request,
Writer writer)
{
writer.write(String.format(
"{\"error\":{\"java.class\":\"%s\", \"message\":\"%s\"}}",
e.getClass(), e.getMessage()));
}