Created
February 2, 2021 12:21
-
-
Save projected1/f309586edff686fec0b2da145605eece to your computer and use it in GitHub Desktop.
Unwinds Java exception stack and converts it to a formatted string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Unwinds Java exception stack and converts it to a formatted string. | |
* | |
* e.g. | |
* | |
* Exception in thread "main" | |
* java.lang.RuntimeException: java.lang.RuntimeException: test | |
* at com.example.Main.foo(Main.java:50) | |
* at com.example.Main.test(Main.java:40) | |
* at com.example.Main.main(Main.java:14) | |
* Caused by: java.lang.RuntimeException: java.lang.RuntimeException: test | |
* java.lang.RuntimeException: test | |
* at com.example.Main.bar(Main.java:55) | |
* at com.example.Main.foo(Main.java:48) | |
* at com.example.Main.test(Main.java:40) | |
* at com.example.Main.main(Main.java:14) | |
*/ | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.function.Function; | |
import java.util.stream.Collectors; | |
String formatException(Throwable e) { | |
Function<Throwable, String> toStackTrace = e1 -> | |
e1 + "\n\tat " + Arrays.stream(e1.getStackTrace()) | |
.map(StackTraceElement::toString) | |
.collect(Collectors.joining("\n\tat ")) + "\n"; | |
Function<Throwable, String> unwindCause = e1 -> { | |
var cause = new ArrayList<String>(); | |
while (e1.getCause() != null) { | |
cause.add("Caused by: " + e1 + "\n" + toStackTrace.apply(e1.getCause())); | |
e1 = e1.getCause(); | |
} | |
return String.join("\n", cause) + "\n"; | |
}; | |
return "Exception in thread " + | |
"\"" + Thread.currentThread().getName() + "\"\n" + | |
toStackTrace.apply(e) + | |
unwindCause.apply(e); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment