What is the easiest way to convert the result of Throwable.getStackTrace()
to a string that depicts the stacktrace?
if you are using Java 8, try this
Arrays.stream(e.getStackTrace())
.map(s->s.toString())
.collect(Collectors.joining("\n"));
you can find the code for getStackTrace()
function provided by Throwable.java
as :
public StackTraceElement[] getStackTrace() {
return getOurStackTrace().clone();
}
and for StackTraceElement
, it provides toString()
as follows:
public String toString() {
return getClassName() + "." + methodName +
(isNativeMethod() ? "(Native Method)" :
(fileName != null && lineNumber >= 0 ?
"(" + fileName + ":" + lineNumber + ")" :
(fileName != null ? "("+fileName+")" : "(Unknown Source)")));
}
So just join the StackTraceElement
with "\n".