Search code examples
javaexceptiontostringthrowable

Java Exception toString() inclusive causes


Is there any good function collecting all causes of an Exception in a string? The method printStackTrace() collect them with their StackTraces:

   HighLevelException: MidLevelException: LowLevelException
           at Junk.a(Junk.java:13)
           at Junk.main(Junk.java:4)
   Caused by: MidLevelException: LowLevelException
           at Junk.c(Junk.java:23)
           at Junk.b(Junk.java:17)
           at Junk.a(Junk.java:11)
           ... 1 more
   Caused by: LowLevelException
           at Junk.e(Junk.java:30)
           at Junk.d(Junk.java:27)
           at Junk.c(Junk.java:21)
           ... 3 more

But I just want the getMessage() of the causes:

   HighLevelException: MidLevelException: LowLevelException
   Caused by: MidLevelException: LowLevelException
   Caused by: LowLevelException

Should I write my own function?


Solution

  • Yes, you'll have to write a simple method for that

    static String message(Throwable e) {
        StringBuilder sb = new StringBuilder();
        sb.append(e.getMessage());
        Throwable t = e.getCause();
        while (t != null) {
            sb.append("\nCaused by: ").append(t.getMessage());
            t = t.getCause();
        }
        return sb.toString();
    }