27

我想知道如何抛出 "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
4

7 回答 7

38

我认为你需要的是:

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"]
}
于 2013-04-13T11:33:13.740 回答
3

您可以通过这种方式更好地使用它,将message()先前Exception的与您正在使用message()的新的合并:Exceptionthrow

      } catch (Exception e) {
          throw new Exception("FIRST EXCEPTION" + e.getMessage(), e);
      }
于 2013-04-13T11:27:36.497 回答
1

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

    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);
    }

哪个打印

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

于 2013-04-13T11:31:07.657 回答
1

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

这是一个例子:

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:第三个异常+第二个异常+第一个异常

于 2013-04-13T11:34:55.827 回答
1

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

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
于 2021-01-24T16:26:50.410 回答
0

我使用以下示例将所有属性保存在类对象中:

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; 
    }
于 2018-03-30T20:11:43.427 回答
0

也许更简单

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);
}
于 2022-01-24T15:00:49.747 回答