How can I convert a stack trace to a string?

前端 未结 30 1206
再見小時候
再見小時候 2020-11-22 14:51

What is the easiest way to convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace?

30条回答
  •  太阳男子
    2020-11-22 15:05

    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".

提交回复
热议问题