获取异常堆栈信息工具类【我】

    //截取前300个字符,将异常信息存入数据库时避免超出数据库字段长度范围
    public static String getE(Exception e) {
        String s = getStackTraceInfo(e);
        if (s.length()>=300) {
            return s.substring(0, 300);
        }
        return s;
    }
    
      /**
     * 获取e.printStackTrace() 的具体信息,赋值给String 变量,并返回
     * 
     * @param e
     *            Exception
     * @return e.printStackTrace() 中 的信息
     */
    public static String getStackTraceInfo(Exception e) {

        StringWriter sw = null;
        PrintWriter pw = null;

        try {
            sw = new StringWriter();
            pw = new PrintWriter(sw);
            e.printStackTrace(pw);//将出错的栈信息输出到printWriter中
            pw.flush();
            sw.flush();

            return sw.toString();
        } catch (Exception ex) {

            return "发生错误";
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (pw != null) {
                pw.close();
            }
        }

    }
原文地址:https://www.cnblogs.com/libin6505/p/11095356.html