【问题标题】:Get detail messages of chained exceptions Java获取链式异常 Java 的详细消息
【发布时间】:2013-04-13 11:24:24
【问题描述】:

我想知道如何抛出“final”Exception,其中包含一条详细消息,其中包含许多连锁异常的所有详细消息。

例如假设这样的代码:

try {
  try {
    try {
      try {
        //Some error here
      } catch (Exception e) {
        throw new Exception("FIRST EXCEPTION", e);
      }
    } catch (Exception e) {
      throw new Exception("SECOND EXCEPTION", e);
    }
  } catch (Exception e) {
    throw new Exception("THIRD EXCEPTION", e);
  }
} catch (Exception e) {
  String allMessages = //all the messages
  throw new Exception(allMessages, e);
}

我对完整的stackTrace 不感兴趣,我只对消息感兴趣。我的意思是,我想要这样的结果:

java.lang.Exception: THIRD EXCEPTION + SECOND EXCEPTION + FIRST EXCEPTION

【问题讨论】:

    标签: java exception chaining


    【解决方案1】:

    我认为你需要的是:

    public static List<String> getExceptionMessageChain(Throwable throwable) {
        List<String> result = new ArrayList<String>();
        while (throwable != null) {
            result.add(throwable.getMessage());
            throwable = throwable.getCause();
        }
        return result; //["THIRD EXCEPTION", "SECOND EXCEPTION", "FIRST EXCEPTION"]
    }
    

    【讨论】:

    • 优秀的解决方案,谢谢!其他建议也不错,但是这样我将代码集中在一个方法中,我只需要修改我抛出 final Exception... 的方法
    【解决方案2】:

    你可以更好地使用它,将以前的Exceptionmessage() 与新的Exceptionmessage() 合并,你是throwing:

          } catch (Exception e) {
              throw new Exception("FIRST EXCEPTION" + e.getMessage(), e);
          }
    

    【讨论】:

      【解决方案3】:

      遍历异常原因并在每个异常中附加消息。

          try
          {
              try
              {
                  try
                  {
                      try
                      {
                          throw new RuntimeException("Message");
                      }
                      catch (Exception e)
                      {
                          throw new Exception("FIRST EXCEPTION", e);
                      }
                  }
                  catch (Exception e)
                  {
                      throw new Exception("SECOND EXCEPTION", e);
                  }
              }
              catch (Exception e)
              {
                  throw new Exception("THIRD EXCEPTION", e);
              }
          }
          catch (Exception e)
          {
              String message = e.getMessage();
              Throwable inner = null;
              Throwable root = e;
              while ((inner = root.getCause()) != null)
              {
                  message += " " + inner.getMessage();
                  root = inner;
              }
              System.out.println(message);
          }
      

      打印出来的

      第三个异常第二个异常第一个异常消息

      【讨论】:

        【解决方案4】:

        您可以在每个异常上添加上一个异常消息

        这是一个例子:

        public static void main(String[] args) {
        
            try {
                try {
                    try {
                        try {
                            throw new Exception();
                            // Some error here
                        } catch (Exception e) {
                            throw new Exception("FIRST EXCEPTION", e);
                        }
                    } catch (Exception e) {
                        Exception e2 = new Exception("SECOND EXCEPTION + " + e.getMessage());
                        throw e2;
                    }
                } catch (Exception e) {
                    Exception e3 = new Exception("THIRD EXCEPTION + " + e.getMessage());
                    throw e3;
                }
            } catch (Exception e) {
                System.out.println(e);
            }
        }
        

        结果是:java.lang.Exception: THIRD EXCEPTION + SECOND EXCEPTION + FIRST EXCEPTION

        【讨论】:

          【解决方案5】:

          这是一个将链式异常转换为字符串的好工具:

          public final class ThrowableUtil {
          
              private ThrowableUtil() {}
          
              public static String chainedString(@NonNull Throwable throwable) {
                  StringBuilder SB = new StringBuilder(throwable.toString());
                  while((throwable = throwable.getCause()) != null)
                      SB.append("\ncaused by ").append(throwable);
                  return SB.toString();
              }
          
              public static String chainedString(@NonNull String msg, @NonNull Throwable throwable) {
                  StringBuilder SB = new StringBuilder(msg);
                  do {
                      SB.append("\ncaused by ").append(throwable);
                  } while((throwable = throwable.getCause()) != null);
                  return SB.toString();
              }
          
          }
          

          示例输出:

          ThrowableUtil.chainedString(e);
          

          生产

          java.io.IOException: Failed to create required video encoder
          caused by java.lang.RuntimeException: Invalid mime type
          

          另一个示例输出:

          ThrowableUtil.chainedString("Writing of media file failed", e);
          

          生产

          Writing of media file failed
          caused by java.io.IOException: Failed to create required video encoder
          caused by java.lang.RuntimeException: Invalid mime type
          

          【讨论】:

            【解决方案6】:

            我已通过以下示例将所有属性保存在一个类对象中:

            public List<ErrorMessage> getMessageList(Throwable throwable) {
                    List<ErrorMessage> errorMessageList =  new ArrayList<ErrorMessage>();
                    while (throwable != null) {
                        ErrorMessage message = new ErrorMessage();
                        message.set_message( throwable.getMessage());
                        message.set_line(throwable.getStackTrace()[0].getLineNumber());
                        message.set_methodName(throwable.getStackTrace()[0].getMethodName());
                        message.set_fileName(throwable.getStackTrace()[0].getFileName() );
                        message.set_className(throwable.getStackTrace()[0].getClassName());
                        errorMessageList.add(message);
                        throwable = throwable.getCause();
                    }
                    return errorMessageList; 
                }
            

            【讨论】:

              【解决方案7】:

              也许更简单

              try {
                 // code that throws exception
              } catch(Throwable e ) {
                  var messages = new ArrayList<String>();
                  
                  do {
                      messages.add(e.getMessage());
                      e = e.getCause();
                  } while( e!= null ); 
                  
                  var message = String.join(" -> ", messages);    
                  System.out.println(message);
              }
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2013-03-31
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多