【问题标题】:Is there a JAX-RS' ExceptionMapper equivalent for Spring-MVC 3 REST support?Spring-MVC 3 REST 支持是否有 JAX-RS 的 ExceptionMapper 等效项?
【发布时间】:2012-01-17 15:29:27
【问题描述】:

我想在全局级别处理我的异常,但似乎 Spring MVC 仅提供了一种使用 @ExceptionHandler 注释在控制器级别处理异常的方法(对于带有 @ResponseBody 注释的 REST 支持),它不尊重DRY原则。

我阅读了 JAX-RS 文档,发现 ExceptionMapper 可以完美地满足我的需求……但我需要一个与 Spring MVC 3 等效的产品。

有解决办法吗?

谢谢。

【问题讨论】:

    标签: java rest spring-mvc exception-handling


    【解决方案1】:

    我终于通过在 Spring Javadoc 中搜索找到了响应。

    事实上,我不得不重写 DefaultHandlerExceptionResolver。

    然后您必须在您的 Web 应用程序上下文中声明您的新 ExceptionResolver。

    所以,当你在 Controller 中抛出 MyNewException1 时,Spring MVC 可以处理它。

     @Override
    protected ModelAndView doResolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {
    
        try {
            if (ex instanceof MyNewException1) {
                return handleMyNewException1((MyNewException1) ex, request, response,
                        handler);
            }
            else if (ex instanceof MyNewException2) {
                return handleMyNewException2((MyNewException2) ex, request,
                        response, handler);
            }
        } catch (IOException handlerException) {
            logger.warn("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException);
            return null;
        } 
    
        return super.doResolveException(request, response, handler, ex);
    } 
    
    protected ModelAndView handleMyNewException1(MyNewException1 ex,
            HttpServletRequest request, HttpServletResponse response,
            Object handler) throws IOException {
                //For example send a bad request code error
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
        return new ModelAndView();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-22
      • 2019-10-04
      • 2014-01-24
      • 1970-01-01
      • 1970-01-01
      • 2012-03-19
      • 2014-10-22
      • 2017-07-18
      • 1970-01-01
      相关资源
      最近更新 更多