gpt4 book ai didi

rest - Spring @ExceptionHandler 不适用于 @ResponseBody

转载 作者:行者123 更新时间:2023-12-02 15:42:49 25 4
gpt4 key购买 nike

我尝试为剩余 Controller 配置一个 spring 异常处理程序,该 Controller 能够根据传入的接受 header 将映射渲染到 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;
}

在同一个 Controller 中,通过相应的转换器将响应映射到 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 方法只有两种有效的返回类型:

  • 字符串
  • 模型和 View 。

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

The return type can be a String, which is interpreted as a view name or a ModelAndView object.

回复评论

Thanx, seems I overread this. That's bad... any ideas how to provides exceptions automatically in xml/json format? – Sven Haiges 7 hours ago

这就是我所做的(我实际上是在 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()));
}

关于rest - Spring @ExceptionHandler 不适用于 @ResponseBody,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5097134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com