相关疑难解决方法(0)

Spring @ExceptionHandler不能与@ResponseBody一起使用

我尝试为休息控制器配置一个spring异常处理程序,该处理程序能够根据传入的accept头将映射呈现给xml和json.它现在抛出500个servlet异常.

这工作,它拿起home.jsp:

@ExceptionHandler(IllegalArgumentException.class)
public String handleException(final Exception e, final HttpServletRequest request, Writer writer)
{
    return "home";
}
Run Code Online (Sandbox Code Playgroud)

这不起作用:

@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;
}
Run Code Online (Sandbox Code Playgroud)

在同一控制器中,通过相应的转换器将响应映射到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");
}
Run Code Online (Sandbox Code Playgroud)

任何人?

rest spring-mvc

26
推荐指数
5
解决办法
5万
查看次数

标签 统计

rest ×1

spring-mvc ×1