2

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?

Olivier Faucheux
  • 2,520
  • 3
  • 29
  • 37
  • Yes you should. If you want that in a log file though, depending on the log framework you may be able to use the correct template to log the exception as you want. – Michael Laffargue Jul 31 '13 at 06:52

2 Answers2

6

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();
}
Tala
  • 8,888
  • 5
  • 34
  • 38
1

You can create a custom exception and override the getMessage() function.

here is a sample where I am collecting Stacktraces:

@Override
public String getMessage()
{
    for (StackTraceElement element : this.getStackTrace() ){
              result.append( element );
              result.append( NEW_LINE );
            }
            return result.toString();
}

You can use your own version of code to fit your requirement.

Learn More
  • 1,535
  • 4
  • 29
  • 51