Mik*_*ikO 22 java exception-handling exception chaining
我想知道我如何能够选择"最终" 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);
}
Run Code Online (Sandbox Code Playgroud)
我对完整不感兴趣stackTrace,但只是在我写的信息中.我的意思是,我想得到这样的结果:
java.lang.Exception: THIRD EXCEPTION + SECOND EXCEPTION + FIRST EXCEPTION
Run Code Online (Sandbox Code Playgroud)
卢声远*_* Lu 31
我想你需要的是:
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"]
}
Run Code Online (Sandbox Code Playgroud)