【问题标题】:Java - find the first cause of an exceptionJava - 找到异常的第一个原因
【发布时间】:2010-12-19 23:33:39
【问题描述】:

我需要检查异常是否是由某些数据库问题引起的。我收到一个异常并检查其原因是否包含“ORA”字符串并返回它(类似于“ORA-00001”)。这里的问题是我收到的异常嵌套在其他异常中,所以如果我不知道它是否是 oracle 异常,我必须检查该异常的原因等等。 有没有更清洁的方法来做到这一点?有没有办法知道给定异常的第一个原因(深层嵌套异常)?

我当前的代码如下所示:

private String getErrorOracle(Throwable e){
        final String ORACLE = "ORA";
        if (e.getCause() != null && e.getCause().toString().contains(ORACLE)){
            return e.getCause().toString();
        } else if(e.getCause() != null){
            return getErrorOracle(e.getCause());
        } else {
            return null;
        }
    }

【问题讨论】:

    标签: java oracle exception-handling ora-00001


    【解决方案1】:

    只需遍历异常链,直到您无缘无故地遇到异常,然后返回该消息,如果您想要最后一条消息。

    你的函数只会得到第一个原因,如果有的话。

    您可能希望在您的程序包中找到第一个原因,因为实际最深的原因可能是 oracle 异常,这很有帮助,但除非您能看到问题出在哪里,否则您将很难修复它。

    【讨论】:

    • 谢谢。我想我会走这条路。我必须这样做,因为当异常是由与数据库相关的任何问题引起时,客户希望显示一些特定的消息。当我收到异常时,我不知道它是否是由数据库引起的,因为第一个异常嵌套在异常链中,所以我正在寻找解决这个问题的方法。
    • 嗯,他的方法是递归的,所以他会得到根本原因。
    • @Bozho - 他有三个带有返回的 if 语句。如果他让它再次调用自己,那么它将是递归的,但是,他需要改变他的逻辑,所以它会退出。
    • 第二个 if 语句确实调用了自己并且逻辑看起来正确,我不明白为什么这找不到正确的异常。
    【解决方案2】:

    你可以使用 Throwable 类中的getStackTrace()。这将为您提供可使用的 StackTraceElements 堆栈。您可以遍历 StackTraceElements[] 以找到“ORA”字符串。

    如果您需要示例,请告诉我。

    【讨论】:

      【解决方案3】:

      我认为 oracle 抛出的任何错误都将包含在 SQLException 中(如果有错误,请有人纠正我)。访问 SQLException 后,您应该可以调用

      getErrorCode() 检索此 SQLException 对象的特定于供应商的异常代码。

      让我知道这是否可行,因为我从未尝试过:-)

      卡尔

      【讨论】:

      • 是的。似乎Oracle抛出的异常扩展了SQLException。关于 getErrorCode() 这似乎返回一个数字,我想你是对的。我明天上班时检查一下。谢谢。
      【解决方案4】:

      如果抛出的异常总是属于特定类型,例如 OracleException,您可以只捕获该异常。

      例如:

      try {
      
          ...
      
      } catch(OracleException oe) {
      
          ...
      
      }
      

      这仅适用于抛出特定 Oracle 异常的情况。我对 Oracle 了解不多,因此在尝试此操作之前,您可能想知道是否发生了这种情况。

      【讨论】:

        【解决方案5】:

        您可以改进对SQLException 的代码检查

        import java.sql.SQLException;
        
        private static final String ORACLE = "ORA";
        
        public String doHandle(Throwable t) {
            if (t.getClass().isAssignableFrom(SQLException.class)) {
            SQLException e = (SQLException) t;
            int errCode = e.getErrorCode();
            String state = e.getSQLState();
            String msg = e.getMessage();
            if (msg.contains(ORACLE)) {
                return msg;
                }
            } else {
                if (t.getCause() != null) {
                    return this.doHandle(t.getCause());
                    }
                }
            return "";
        }
        

        另外,我认为 Oracle 中的“errCode”包含与 ORA-nnnn 关联的数字

        【讨论】:

        • 谢谢。这对我改进功能有很大帮助。我刚刚将“t.getClass().isAssignableFrom(SQLException.class)”更改为“t instaceof SQLException”,因为第一个没有被评估为真(我正在测试的异常是 BatchUpdateException)
        【解决方案6】:

        您的使用可能有点矫枉过正,但我​​认为它更清洁(并且可重复使用)

        interface ThrowablePredicate {
            boolean accept(Throwable t);
        }
        
        public OracleErrorThrowablePredicate implements ThrowablePredicate {
            private static final ORA_ERR = "ORA";
        
            public boolean accept(Throwable t) {
                return t.toString().contains(ORA_ERR);
            }
        }
        
        
        public class CauseFinder {
        
           private ThrowablePredicate predicate;
        
           public CauseFinder(ThrowablePredicate predicate) {
              this.predicate = predicate;
           }
        
           Throwable findCause(Throwable t) {
              Throwable cause = t.getCause();
        
              return cause == null ? null 
                 : predicate.accept(cause) ? cause : findCause(cause)
           }
        }
        
        
        // Your method
        private String getErrorOracle(Throwable e){
            return new CauseFinder(new OracleErrorThrowablePredicate()).findCause(e);
        }
        

        【讨论】:

          【解决方案7】:

          为了不重新发明轮子,如果您使用的是Apache Commons Lang,请查看ExceptionUtils.getRootCause()。

          是否值得为此包含一个库?也许不吧。但是如果你已经在你的类路径中拥有它,它就在那里,并注意它做了一些“天真的”实现可能不会做的事情(例如处理原因链中的循环......呃!)

          【讨论】:

            【解决方案8】:

            如果您已经在Guava 上,那么Throwables.getRootCause() 会来救援。

            【讨论】:

            • Guava 的实现不考虑原因链中的循环。
            【解决方案9】:

            2015 年 1 月 28 日,我无法使用上述任何解决方案解决我的问题,所以我的建议是使用:

            e.getMessage().toString();
            

            Ps:我在安卓上使用它。

            【讨论】:

            • .toString() 是多余的,除了这不符合要求。
            【解决方案10】:

            使用核心 Java API 的一条线解决方案:

                try {
                    i = 1 / 0; 
                } catch (ArithmeticException e) {
                    System.out.println(new ArithmeticException().initCause(e).getCause());
                }
            

            以下另一种解决方案也适用:

                try {
                    i = 1 / 0; 
                } catch (ArithmeticException e) {
                    System.out.println(new Exception().initCause(e).getCause());
                }
            

            它们都会打印

            java.lang.ArithmeticException: / 为零

            【讨论】:

              【解决方案11】:

              在我的 getRootCause IDEA 的 Spring Boot 项目中建议 3 静态导入:

              弹簧芯:org.springframework.core.NestedExceptionUtils.getRootCause
              杰克逊:com.fasterxml.jackson.databind.util.ClassUtil.getRootCause
              番石榴(Swagger 传递)com.google.common.base.Throwables.getRootCause

              最聪明的(带有循环检查)是 Spring NestedExceptionUtils.getRootCause。 但是,如果您的异常没有原因,则方法返回 null。 就我而言,这是错误的,所以我已经完成了:

              @NonNull
              public static Throwable getRootCause(@NonNull Throwable t) {
                  Throwable rootCause = NestedExceptionUtils.getRootCause(t);
                  return rootCause != null ? rootCause : t;
              }
              

              【讨论】:

                【解决方案12】:

                我想添加 Kotlin 扩展函数来获取根本原因:

                fun Throwable.rootCause(): Throwable {
                  return if (cause == null) this else cause!!.rootCause()
                }
                
                //Return null if first cause is null
                fun Throwable.optRootCause(): Throwable? {
                  return if (cause == null) null else cause!!.rootCause()
                }
                

                如果需要在可投掷链中的任何点找到原因,或者这个:

                fun <T : Throwable> Throwable.isOrContainsCauseOfType(clazz: KClass<T>): Throwable?  {
                  return when {
                    clazz.isInstance(this) -> this //remove if you want to exclude [this]
                    cause == null -> null
                    clazz.isInstance(cause) -> cause
                    else -> cause!!.isOrContainsCauseOfType(clazz)
                  }
                }
                

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2020-08-14
                  • 1970-01-01
                  • 1970-01-01
                  • 2012-11-06
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2012-03-10
                  相关资源
                  最近更新 更多