Skip to content

Instantly share code, notes, and snippets.

@projected1
Created February 2, 2021 12:21
Show Gist options
  • Save projected1/f309586edff686fec0b2da145605eece to your computer and use it in GitHub Desktop.
Save projected1/f309586edff686fec0b2da145605eece to your computer and use it in GitHub Desktop.
Unwinds Java exception stack and converts it to a formatted string.
/**
* 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