package com.bcxin.message.common.utils;


import java.io.Closeable;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 异常帮助类
 */
public abstract class ExceptionUtils {
    /**
     * 获取异常堆栈字符串新
     *
     * @param ex
     * @return
     */
    public static String getExceptionMessage(Throwable ex) {
        if (ex == null) {
            // 如果异常为空返回空字符串
            return "";
        }
        StringWriter outputStream = null;
        PrintWriter printWriter = null;
        try {
            outputStream = new StringWriter();
            printWriter = new PrintWriter(outputStream, true);
            ex.printStackTrace(printWriter);
            printWriter.flush();
            outputStream.flush();
            return outputStream.toString();
        } catch (Exception e) {
            // 如果错误，那么直接返回异常类名称
            return ex.getClass().getName();
        } finally {
            closeStream(outputStream);
            closeStream(printWriter);
        }
    }

    /**
     * 关闭流
     *
     * @param stream
     */
    public static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                // 忽略异常
            }
        }
    }
}
