将Throwable.getStackTrace()的结果转换为描述堆栈跟踪的字符串最简单的方法是什么?


当前回答

我想知道为什么没有人提到ExceptionUtils.getStackFrames(exception)

对我来说,这是将堆栈跟踪及其所有原因转储到底的最方便方法:

String.join("\n", ExceptionUtils.getStackFrames(exception));

其他回答

使用Throwable.printStackTrace(PrintWriter pw)将堆栈跟踪发送到适当的编写器。

import java.io.StringWriter;
import java.io.PrintWriter;

// ...

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String sStackTrace = sw.toString(); // stack trace as a string
System.out.println(sStackTrace);

我想知道为什么没有人提到ExceptionUtils.getStackFrames(exception)

对我来说,这是将堆栈跟踪及其所有原因转储到底的最方便方法:

String.join("\n", ExceptionUtils.getStackFrames(exception));

Kotlin>=1.4

在Throwable上使用内置函数stackTraceToString()。

Kotlin<1.4

扩展Throwable类将提供String属性error.stackTraceString:

val Throwable.stackTraceString: String
  get() {
    val sw = StringWriter()
    val pw = PrintWriter(sw)
    this.printStackTrace(pw)
    return sw.toString()
  }

我的oneliner将堆栈跟踪转换为封闭的多行字符串:

Stream.of(e.getStackTrace()).map((a) -> a.toString()).collect(Collectors.joining("\n", "[", "]"))

易于传递给记录器“原样”。

警告:这可能有点离题,但哦,好吧…;)

我不知道最初的海报是什么原因让堆栈跟踪成为字符串。当堆栈跟踪应该以SLF4J/Logback LOG结尾,但没有或应该抛出异常时,我会这样做:

public void remove(List<String> ids) {
    if(ids == null || ids.isEmpty()) {
        LOG.warn(
            "An empty list (or null) was passed to {}.remove(List). " +
            "Clearly, this call is unneccessary, the caller should " + 
            "avoid making it. A stacktrace follows.", 
            getClass().getName(),
            new Throwable ("Stacktrace")
        );

        return;
    }

    // actual work, remove stuff
}

我喜欢它,因为它不需要外部库(当然,除了您的日志后端,它大部分时间都会在那里)。