獲取異常信息,返回一個map
package ;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.HashMap;
import java.util.Map;
import com.cntaiping.tpi.exception.BaseDataException;
import com.cntaiping.tpi.exception.BusinessCheckException;
/**
* 異常公共服務類
* @author Alex
*
*/
public class ExceptionUtils {
/**
* 獲取異常信息內容
* @param isAll:true:全部異常 false:第一條異常
* @param ex
* @return
* @throws Exception
*/
public static Map<String,String> getExceptionMsg(Exception ex){
StringBuilder message = new StringBuilder();
Map<String,String> msgMap = new HashMap<String,String>();
String exceptionType = "";
String exceptionMessage = "";
if(ex instanceof BusinessCheckException ){
msgMap.put("ExceptionMsg", ex.getMessage());
msgMap.put("ErrorCode", ((BusinessCheckException) ex).getErrorCode());
}else if(ex instanceof BaseDataException){
msgMap.put("ExceptionMsg", ex.getMessage());
msgMap.put("ErrorCode", ((BaseDataException) ex).getErrorCode());
}else{
if(exceptionMessage == null || "".equals(exceptionMessage)){
StringWriter out = new StringWriter();
ex.printStackTrace(new PrintWriter(out));
message.append((out.toString()));
msgMap.put("ExceptionList", message.toString());
msgMap.put("ErrorCode", "9999");
}else{
msgMap.put("ExceptionMsg", exceptionType + " " + exceptionMessage.toString());
msgMap.put("ErrorCode", "9999");
}
}
return msgMap;
}
public static Exception unwrapThrowable(Exception wrapped) {
Exception unwrapped = wrapped;
while (true) {
if (unwrapped instanceof InvocationTargetException) {
unwrapped = (Exception) ((InvocationTargetException) unwrapped)
.getTargetException();
} else if (unwrapped instanceof UndeclaredThrowableException) {
unwrapped = (Exception) ((UndeclaredThrowableException) unwrapped)
.getUndeclaredThrowable();
} else {
return unwrapped;
}
}
}
/**
* 將異常堆棧轉換爲字符串
* @param aThrowable 異常
* @return String
*/
public static String getStackTrace(Throwable aThrowable) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
aThrowable.printStackTrace(printWriter);
return result.toString();
}
}