有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java对于SpringMVC3REST支持是否有JAXRS的ExceptionMapper等价物?

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

我阅读了JAX-RS文档,发现ExceptionMapper是对我需求的完美回应。。。但我需要一个与Spring MVC 3相当的版本

有解决办法吗

谢谢


共 (1) 个答案

  1. # 1 楼答案

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

    事实上,我必须重写DefaultHandlerExceptionResolver

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

    因此,当在控制器中抛出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();
    }