Java,Exception,StringWriter,将异常信息转化为字符串

  • A+
所属分类:体育平台

Java,Exception,StringWriter,将异常信息转化为字符串

说明

系统日志,将异常信息转换成字符串,便于记录。

代码

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

public class ThrowableUtil {

    /**
     * 将异常信息转化为字符串
     *
     * @param throwable 异常对象
     * @return 异常信息字符串
     */
    public static String throwableToString(Throwable throwable) {
        try (StringWriter stringWriter = new StringWriter();
             PrintWriter writer = new PrintWriter(stringWriter)) {
            throwable.printStackTrace(writer);
            StringBuffer buffer = stringWriter.getBuffer();
            return buffer.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        System.out.println(throwableToString(new RuntimeException()));
    }
}

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: