获取包含内部异常的完整字符串堆栈跟踪 [英] Getting full string stack trace including inner exception

查看:121
本文介绍了获取包含内部异常的完整字符串堆栈跟踪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java的e.printStackTrace()不会打印内部异常堆栈跟踪的所有细节。

Java's e.printStackTrace() doesn't print all the details of the inner exception's stack trace.

有没有一种方法可以生成完整的堆栈跟踪字符串形式? (除了自己格式化)

Is there a ready way to generate the complete stack trace in string form? (besides formatting it myself)

编辑

我刚刚发现了printStackTrace ()确实 - 它过滤掉的堆栈帧正好是内部异常和外部异常共有的堆栈帧。所以其实这是相当我想要的东西,而不是 '完全' 堆栈跟踪。

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.

推荐答案

我结束了我自己的滚动(我把Throwable.printStackTrace()的执行情况和调整它位):

I ended up rolling my own (I took the implementation of Throwable.printStackTrace() and tweaked it a bit):

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();
    }
}

这篇关于获取包含内部异常的完整字符串堆栈跟踪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆