將異常對象轉爲字符串

/**
     * 將異常對象轉爲字符串。
     *
     * @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());
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章