Spring @ExceptionHandler does not work with @ResponseBody

后端 未结 7 1604
南笙
南笙 2020-11-29 23:45

I try to configure a spring exception handler for a rest controller that is able to render a map to both xml and json based on the incoming accept header. It throws a 500 se

7条回答
  •  伪装坚强ぢ
    2020-11-30 00:47

    Your method

    @ExceptionHandler(IllegalArgumentException.class)
    public @ResponseBody Map handleException(final Exception e, final HttpServletRequest request, Writer writer)
    

    does not work because it has the wrong return type. @ExceptionHandler methods have only two valid return types:

    • String
    • ModelAndView.

    See http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html for more information. Here's the specific text from the link:

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

    In response to the comment

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

    Here's what I've done (I've actually done it in Scala so I'm not sure if the syntax is exactly correct, but you should get the gist).

    @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()));
    }
    

提交回复
热议问题