Exception
連鎖した多数の例外の詳細なメッセージをすべて含む「final」をスローする方法を知りたいです。
たとえば、次のようなコードを考えます。
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
ベストアンサー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"]
}