How can I convert a stack trace to a string?

前端 未结 30 1162
再見小時候
再見小時候 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:16

    an exapansion on Gala's answer that will also include the causes for the exception:

    private String extrapolateStackTrace(Exception ex) {
        Throwable e = ex;
        String trace = e.toString() + "\n";
        for (StackTraceElement e1 : e.getStackTrace()) {
            trace += "\t at " + e1.toString() + "\n";
        }
        while (e.getCause() != null) {
            e = e.getCause();
            trace += "Cause by: " + e.toString() + "\n";
            for (StackTraceElement e1 : e.getStackTrace()) {
                trace += "\t at " + e1.toString() + "\n";
            }
        }
        return trace;
    }
    

提交回复
热议问题