2

I'm using SpringMVC and I want to handle exception on rest controller. My controller usually write a json in response output, but when exception occurs I'm unable to catch it and tomcat html page is returned.

How I can catch global exceptions and return appropriate response based on "accept" parameter in request?

4

3 に答える 3

1

もう 1 つのアプローチ (私が使用しているもの) は、グローバル例外ハンドラーを作成し、それを使用する必要があることを Spring に伝えることです。そうすれば、コントローラ メソッドに@ExceptionHandler. 簡単な例を次に示します。

public class ExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse response, Object o, Exception e) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // Or some other error code
        ModelAndView mav = new ModelAndView(new MappingJackson2JsonView());
        mav.addObject("error", "Something went wrong: \"" + e.getMessage() + "\"");
        return mav;
    }
}

そして、<something>-servlet.xmlそれを必要な例外リゾルバーとして割り当てます:

<!-- Define our exceptionHandler as the resolver for our program -->
<bean id="exceptionResolver" class="tld.something.ExceptionHandler" />

次に、すべての例外が Exceptionhandler に送信され、そこでリクエストを確認して、ユーザーへの返信方法を決定できます。私の場合、私はジャクソンを使用しています。

于 2013-04-30T15:46:56.703 に答える