自定义类库:java将异常信息转换成字符串

一、在日志上打印异常信息时,可以将异常信息转换成字符串,便于记录

package com.moy.custom.log;

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

/**
 * [Project]:moy-gradle-project  <br/>
 * [Email]:moy25@foxmail.com  <br/>
 * [Date]:2018/4/8  <br/>
 * [Description]:  <br/>
 *
 * @author YeXiangYang
 */
public abstract class ThrowableUtils {

    /**
     * 将异常信息转化为字符串
     *
     * @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);
        }
    }
}

 

yexiangyang

moyyexy@gmail.com


 

posted @ 2018-04-11 14:09  墨阳  阅读(1670)  评论(0编辑  收藏  举报