一、前言
通过apache的commons-lang包的org.apache.commons.lang.exception.ExceptionUtils自定义HcExceptionUtils异常工具类,将异常栈转换为字符串、获取简单堆栈异常信息等不同应用场景情况,详情代码示例。
二、代码示例
package exception;@b@@b@import java.util.HashMap;@b@import java.util.Map;@b@import org.apache.commons.lang.exception.ExceptionUtils;@b@@b@public class HcExceptionUtils {@b@ @b@ public static Throwable getRootCauseOrSelf(Throwable throwable) {@b@ Throwable[] ta = ExceptionUtils.getThrowables(throwable);@b@ return ((ta.length < 1) ? throwable : ta[(ta.length - 1)]);@b@ }@b@@b@ public static String getRootCauseStackTrace(Throwable throwable) {@b@ Throwable t = getRootCauseOrSelf(throwable);@b@ return ExceptionUtils.getStackTrace(t);@b@ }@b@@b@ public static String getExceptionMsg(Throwable throwable) {@b@ Throwable[] ta = ExceptionUtils.getThrowables(throwable);@b@@b@ StringBuffer exceptionMsgBf = new StringBuffer(throwable.getMessage());@b@ if (ta.length > 1)@b@ exceptionMsgBf.append(ta[(ta.length - 1)].getMessage());@b@@b@ return exceptionMsgBf.toString();@b@ }@b@@b@ public static String getExceptionString(Throwable throwable) {@b@ Throwable[] ta = ExceptionUtils.getThrowables(throwable);@b@@b@ StringBuffer exceptionMsgBf = new StringBuffer(@b@ toSimpleString(throwable));@b@@b@ if (ta.length > 1)@b@ exceptionMsgBf.append(toSimpleString(ta[(ta.length - 1)]));@b@@b@ return exceptionMsgBf.toString();@b@ }@b@@b@ public static String toSimpleString(Throwable throwable) {@b@ String s = throwable.getClass().getName();@b@ String message = throwable.getLocalizedMessage();@b@ return ((message != null) ? s + ": " + message : s);@b@ }@b@@b@ public static Map handleRequestException(String errorCode, String errorMsg,@b@ Map data) {@b@ Map exceptionHandleMap = new HashMap();@b@@b@ exceptionHandleMap.put("status", "0");@b@@b@ exceptionHandleMap.put("errorCode", errorCode);@b@ exceptionHandleMap.put("errorMsg", errorMsg);@b@ return exceptionHandleMap;@b@ }@b@ @b@}