How can I convert a stack trace to a string?

2018-12-31 19:17发布

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

28条回答
情到深处是孤独
2楼-- · 2018-12-31 20:05

Print the stacktrace to a PrintStream, then convert it to a String

// ...

catch (Exception e)
{
    ByteArrayOutputStream out = new ByteArrayOutputStream(); 
    e.printStackTrace(new PrintStream(out));
    String str = new String(out.toByteArray());

    System.out.println(str);
}
查看更多
与君花间醉酒
3楼-- · 2018-12-31 20:05

Warning: This may be a bit off topic, but oh well... ;)

I don't know what the original posters reason was for wanting the stack trace as string in the first place. When the stack trace should end up in an SLF4J/Logback LOG, but no exception was or should be thrown here's what I do:

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
}

I like it because it does not require an external library (other than your logging backend, which will be in place most of the time anyway, of course).

查看更多
无与为乐者.
4楼-- · 2018-12-31 20:06

For me the cleanest and easiest way was:

import java.util.Arrays;
Arrays.toString(e.getStackTrace());
查看更多
冷夜・残月
5楼-- · 2018-12-31 20:06

The following code allows you to get the entire stackTrace with a String format, without using APIs like log4J or even java.util.Logger:

catch (Exception e) {
    StackTraceElement[] stack = e.getStackTrace();
    String exception = "";
    for (StackTraceElement s : stack) {
        exception = exception + s.toString() + "\n\t\t";
    }
    System.out.println(exception);
    // then you can send the exception string to a external file.
}
查看更多
只靠听说
6楼-- · 2018-12-31 20:06

Kotlin

Extending the Throwable class will give you the String property error.stackTraceString:

val Throwable.stackTraceString: String
  get() {
    val sw = StringWriter()
    val pw = PrintWriter(sw)
    this.printStackTrace(pw)
    return sw.toString()
  }
查看更多
还给你的自由
7楼-- · 2018-12-31 20:07

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;
}
查看更多
登录 后发表回答