将异常对象转为字符串

/**
     * 将异常对象转为字符串。
     *
     * @param ex 异常信息
     * @return 字符串
     */
    public static String exceptionToString(Throwable ex) {
        //获取指定Throwable对象中最底层的Throwable
        Throwable lowerThrowable = getLowerThrowable(ex);

        //获取异常堆栈信息。
        StringBuilder sb = new StringBuilder(81920);
        exceptionToString(ex, lowerThrowable, sb);

        return sb.toString();
    }

    /**
     * 将异常对象转为字符串。
     *
     * @param ex 异常信息
     * @return 字符串
     */
    private static void exceptionToString(Throwable ex, Throwable lowerThrowable, StringBuilder sb) {
        sb.append(ex.toString());
        sb.append(SystemCharUtils.getNewLine());

        if (ex.equals(lowerThrowable)) {
            for (StackTraceElement el : ex.getStackTrace()) {
                sb.append(el.toString());
                sb.append(SystemCharUtils.getNewLine());
            }
        }

        if (null != ex.getCause()) {
            exceptionToString(ex.getCause(), lowerThrowable, sb);
        }
    }

    /**
     * 获取指定Throwable对象中最底层的Throwable。
     *
     * @param e Throwable对象
     * @return 最底层的Throwable
     */
    public static Throwable getLowerThrowable(Throwable e) {
        if (null == e.getCause()) {
            return e;
        }

        return getLowerThrowable(e.getCause());
    }

 

posted @ 2020-01-03 17:32  有容乃大  阅读(768)  评论(0编辑  收藏  举报