Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top