Java Tools(三)异常信息转字符串 (来自阿里DataX的代码)

有时候需要把异常信息打印在日志上,e.toString() e.getMessage()获取的信息都太少
看着DataX中有这么一段代码,拿出来记录下,代码上没写作者。
效果:
Java Tools(三)异常信息转字符串 (来自阿里DataX的代码)_第1张图片
com.alibaba.datax.common.exception.ExceptionTracker

package com.alibaba.datax.common.exception;

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

public final class ExceptionTracker {
    public static final int STRING_BUFFER = 1024;

    public static String trace(Throwable ex) {
        StringWriter sw = new StringWriter(STRING_BUFFER);
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        return sw.toString();
    }

    public static void main(String[] args) {
        String str = null;
        try {
            System.out.println(str.length());
        } catch (NullPointerException e) {

            System.out.println("e.toString:"+e.toString());
            System.out.println("---------------------");
            System.out.println("e.getMessage:"+e.getMessage());
            System.out.println("---------------------");
            System.out.println("trace(e):"+trace(e));
        }
    }
}

你可能感兴趣的:(Java)