java 获取完整的字符串堆栈跟踪,包括内部异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1292858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting full string stack trace including inner exception
提问by ripper234
Java's e.printStackTrace() doesn't print all the details of the inner exception's stack trace.
Java 的 e.printStackTrace() 不会打印内部异常堆栈跟踪的所有详细信息。
Is there a ready way to generate the complete stack trace in string form? (besides formatting it myself)
有没有现成的方法可以以字符串形式生成完整的堆栈跟踪?(除了自己格式化)
Edit
编辑
I just found out what printStackTrace() does - apparently the stack frames it filters out are exactly the ones common to the inner exception and the outer one. So in fact it is rather what I want, and not the 'full' stack trace.
我刚刚发现了 printStackTrace() 的作用 - 显然它过滤掉的堆栈帧正是内部异常和外部异常所共有的。所以实际上它是我想要的,而不是“完整的”堆栈跟踪。
采纳答案by ripper234
I ended up rolling my own (I took the implementation of Throwable.printStackTrace() and tweaked it a bit):
我最终滚动了自己的(我采用了 Throwable.printStackTrace() 的实现并对其进行了一些调整):
public static String joinStackTrace(Throwable e) {
StringWriter writer = null;
try {
writer = new StringWriter();
joinStackTrace(e, writer);
return writer.toString();
}
finally {
if (writer != null)
try {
writer.close();
} catch (IOException e1) {
// ignore
}
}
}
public static void joinStackTrace(Throwable e, StringWriter writer) {
PrintWriter printer = null;
try {
printer = new PrintWriter(writer);
while (e != null) {
printer.println(e);
StackTraceElement[] trace = e.getStackTrace();
for (int i = 0; i < trace.length; i++)
printer.println("\tat " + trace[i]);
e = e.getCause();
if (e != null)
printer.println("Caused by:\r\n");
}
}
finally {
if (printer != null)
printer.close();
}
}
回答by Romain Linsolas
I suggest that you use the ExceptionUtilsclass from Apache Commons lang, which provides useful method for that.
我建议您使用Apache Commons lang 中的ExceptionUtils类,它为此提供了有用的方法。
回答by techzen
Yes you can use the StackTraceElement class returned by Throwable.getStackTrace() and find the details.
是的,您可以使用 Throwable.getStackTrace() 返回的 StackTraceElement 类并找到详细信息。
From the API:
从API:
The last element of the array (assuming the array's length is non-zero) represents the bottom of the stack, which is the first method invocation in the sequence.
数组的最后一个元素(假设数组的长度不为零)表示堆栈的底部,这是序列中的第一个方法调用。

