MyStackTrace:
/** * * @author wumingkun * @version 1.0.0 * @Description */ package com.demo.stacktrace; import java.io.PrintStream; /** * @author wumingkun * */ public class MyStackTrace { public static String getStackTrace(Throwable errors) { StringBuffer result = new StringBuffer(); result.append(errors); StackTraceElement[] trace = errors.getStackTrace(); for (int i = 0; i < trace.length; i++) result.append("\n\tat " + trace[i]); Throwable ourCause = errors.getCause(); if (ourCause != null) result.append(getStackTraceAsCause(ourCause, trace)); return result.toString(); } private static String getStackTraceAsCause( Throwable ourCause,StackTraceElement[] causedTrace) { StringBuffer result=new StringBuffer(); StackTraceElement[] trace = ourCause.getStackTrace(); int m = trace.length - 1, n = causedTrace.length - 1; while (m >= 0 && n >= 0 && trace[m].equals(causedTrace[n])) { m--; n--; } int framesInCommon = trace.length - 1 - m; result.append("\nCaused by: " + ourCause); for (int i = 0; i <= m; i++) result.append("\n\tat " + trace[i]); if (framesInCommon != 0) result.append("\n\t... " + framesInCommon + " more"); Throwable tempCause = ourCause.getCause(); if (tempCause != null) result.append(getStackTraceAsCause(tempCause, trace)); return result.toString(); } }
StackTraceTest:
/** * * @author wumingkun * @version 1.0.0 * @Description */ package com.demo.stacktrace; /** * @author wumingkun * */ public class StackTraceTest { /** * @param args */ public static void main(String[] args) { try { m1(); } catch (Exception e) { System.out.println(MyStackTrace.getStackTrace(e));//直接返回异常栈信息字符串 } } /** * */ private static void m1() { StringBuffer sb=null; try { sb.append("aa"); } catch (Exception e) { throw new RuntimeException(e); } } }
重构获取异常栈信息--printStackTrace,布布扣,bubuko.com
时间: 2024-12-09 08:52:33