【问题标题】:Handling all listed exceptions but one with Spring's @ExceptionHandler annotation处理所有列出的异常,但一个使用 Spring 的 @ExceptionHandler 注释
【发布时间】:2013-06-26 10:06:51
【问题描述】:

我指的是 Spring MVC 的 @ExceptionHandler 注释。

我希望我的@ExceptionHandler 注释方法处理所有异常,但一两个将被忽略的特定异常除外。

Spring MVC 3.2 可以做到这一点吗?有什么解决办法吗?

【问题讨论】:

  • 您希望忽略这些异常吗?
  • 我会将用户重定向到自定义错误页面/视图。

标签: spring spring-mvc


【解决方案1】:

为什么不添加两个处理方法,比如

@ExceptionHandler(value={Exception.class})
public ModelAndView all(){
    return new ModelAndView();//return general M&V
}

@ExceptionHandler(value={Ex1.class, Ex2.class})
public ModelAndView special(){
    return new ModelAndView();//return special M&V
}

【讨论】:

    【解决方案2】:

    我认为@ExceptionHandler 注释没有办法做到这一点。

    一种可行的方法是为您提供HandlerExceptionResolver 接口的实现。在您的实现中,您可以提供来自 @ExceptionHandler 方法的代码,并且只为您希望处理的异常执行它。

    我认为让 Spring MVC 获取您的自定义 HandlerExceptionResolver,它只需要在您的 ApplicationContext 中注册为一个 bean。

    【讨论】:

    • AFAIK 这行不通。原因是 @ExceptionHandler 注解的方法优先于 HandlerExceptionResolver。所以任何异常抛出都不会被 HandlerExceptionResolver 捕获。
    • 谢谢 Rob:我们实际上想避免这种情况,但我确实有效。
    • @shazinltc 我认为注册自定义 HandlerExceptionResolver 将删除 Spring MVC 使用的默认 HandlerExceptionResolver 链。 org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver 将成为此链的一部分,因此自定义 HandlerExceptionResolver 应该阻止 ExceptionHandler 功能工作。
    • 但我刚试过。它没有!如果我删除 @ExceptionHandler 带注释的方法,它会起作用
    【解决方案3】:

    我不确定这是否会有所帮助,但这是我会做的。

    @ExceptionHandler(Throwable.class)
    public ModelAndView handleException(Throwable throwable){
    
        if (throwable != null){
            if (throwable instanceof theExceptionYouWantToIgnore){
                return new ModelAndView("customErrorPage");
            }
    //else do your normal business logic and set an appropriate error page
        }
        return errorPage;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-12
      • 2018-11-16
      • 2011-02-21
      • 2020-07-06
      • 2014-05-29
      • 2016-05-18
      • 2012-08-05
      • 2019-11-23
      • 1970-01-01
      相关资源
      最近更新 更多