/* * 只能获取单层异常信息 无法获取caused by * */ public String getExceptionStack(Throwable e){ StackTraceElement[] stackTraceElements = e.getStackTrace(); String prefix = "Exception in thread "+"""+Thread.currentThread().getName()+"" "; String result = prefix+e.toString() + " "; int lenth = stackTraceElements.length - 1; for (int i = 0;i<=lenth;i++){ String err = stackTraceElements[i].getClassName()+"."+stackTraceElements[i].getMethodName()+"("+stackTraceElements[i].getFileName()+"."+stackTraceElements[i].getLineNumber()+")"; result = result + " at "+err+" "; } return result; }
/* * 获取Caused by 参数num要初始化为0 参数hashset要为空hashset * */ public String getExceptionStack(Throwable e, HashSet<String> set,int num){ StackTraceElement[] stackTraceElements = e.getStackTrace(); String prefix = ""; if (num == 0){ prefix = "Exception in thread "+"""+Thread.currentThread().getName()+"" "; } else { prefix = "Caused by: "; } String result = prefix+e.toString() + " "; int lenth = stackTraceElements.length - 1; for (int i = 0;i<=lenth;i++){ String err = stackTraceElements[i].getClassName()+"."+stackTraceElements[i].getMethodName()+"("+stackTraceElements[i].getFileName()+"."+stackTraceElements[i].getLineNumber()+")"; if (set.contains(err)){ continue; } set.add(err); result = result + " at "+err+" "; } Throwable t = e.getCause(); String cause = ""; if (t!=null){ num++; cause = getExceptionStack(t,set,num); } return result + cause; }