Spring @ExceptionHandler 不适用于 @ResponseBody

2023-12-28

我尝试为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 方法只有两种有效的返回类型:

  • String
  • 模型和视图。

See http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html了解更多信息。以下是链接中的具体文本:

返回类型可以是 String,即 被解释为视图名称或 模型和视图对象。

回应评论

谢谢,看来我读过了。那是 不好...任何想法如何提供 xml/json 中自动异常 格式? – 斯文·海格斯 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()));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring @ExceptionHandler 不适用于 @ResponseBody 的相关文章

随机推荐