package com.banking.xc.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
public class ResolveException {
private static String TAG = "ResolveException";
private static int FRIST_LINE = 3;
private static String KEYWORD = "com.jingdong";
public static String resolve(Throwable e) {
try{
StringBuffer exceptionString = new StringBuffer();
resolveCause(e, exceptionString, true);
if (Log.I) {
Log.i(TAG, "size = " + exceptionString.length());
Log.i(TAG, exceptionString.toString());
}
return exceptionString.toString();
}catch(Exception ex){
Writer w = new StringWriter();
ex.printStackTrace(new PrintWriter(w));
return w.toString();
}
}
private static void resolveCause(Throwable cause, StringBuffer sb, boolean isFirst) {
if (cause != null) {
if (!isFirst && cause.getCause() != null) {
resolveCause(cause.getCause(), sb, false);
} else {
sb.append("------" + cause.toString() + "\n");
StackTraceElement[] stack = cause.getStackTrace();
int recordLine = -1;
for (int i = 0; i < stack.length; i++) {
if (i < FRIST_LINE) {
addExceptionString(i, stack, sb);
// if (!isFirst) {
if (stack[i].getClassName().contains(KEYWORD)) {
recordLine = FRIST_LINE;
}
// }
} else {
if (cause.getCause() != null) {// 不是最后一个,则跳出.
break;
}
if (recordLine == -1) {
if (stack[i].getClassName().contains(KEYWORD)) {
recordLine = i;
addExceptionString(i, stack, sb);
}
} else {
if (cause.getCause() == null) {
if (i >= recordLine) {
addExceptionString(i, stack, sb);
}
}
}
}
}
if (cause.getCause() != null) {
resolveCause(cause.getCause(), sb, false);
} else if (recordLine == -1) {
if (Log.V) {
Log.v(TAG, "recordLine == -1recordLine == -1");
}
for (int i = (FRIST_LINE - 1); i < stack.length; i++) {
addExceptionString(i, stack, sb);
}
}
}
}
}
private static void addExceptionString(int index, StackTraceElement[] stack, StringBuffer sb) {
sb.append(stack[index].getClassName() + "." + stack[index].getMethodName() + "(" + stack[index].getLineNumber() + ")" + "\n");
}
}