自定义封装Exception异常抛出
话不多说直接上代码,朋友们可自己测试用于项目:
BaseException类(基础类)
/** *异常处理基类 */ public class BaseException extends RuntimeException { private static final long serialVersionUID = -3653870580234213024L; protected String messageKey; public BaseException() { super(); } public BaseException(String s, Throwable throwable) { super(s, throwable); } public BaseException(Throwable throwable) { super(throwable); } public BaseException(String messageKey) { super(); this.messageKey = messageKey; } /** * 取得异常信息key * @return String */ public String getMessageKey() { return messageKey; } /** * 设置异常信息key * @param messageKey * @return void */ public void setMessageKey(String messageKey) { this.messageKey = messageKey; } @Override public String getMessage() { return messageKey; }
DaoException类 (Dao层)
public class DaoException extends BaseException { private static final long serialVersionUID = -9006104640618533135L; public DaoException(String messageKey) { super.setMessageKey(messageKey); } public DaoException(String messageKey, Throwable t) { super.setMessageKey(messageKey); super.initCause(t); } public DaoException(Throwable t) { super.setMessageKey(t.getClass().getSimpleName()); super.initCause(t); } public Throwable getOrignalException() { Throwable t = this.getCause(); while(t.getCause() != null){ t = t.getCause(); } return t; } public String getOrignalMessageKey() { return this.getOrignalException().getClass().getSimpleName(); } }
ServiceException类(业务层)
public class ServiceException extends BaseException { private static final long serialVersionUID = -9006104640618533135L; public ServiceException(String messageKey) { super(messageKey); } public ServiceException(Throwable t) { if(t instanceof BaseException){ super.setMessageKey(((BaseException) t).getMessageKey()); } super.initCause(t); } public ServiceException(String messageKey, Throwable t) { super.setMessageKey(messageKey); super.initCause(t); } public ServiceException() { } public Throwable getOrignalException() { Throwable t = this.getCause(); while(t.getCause() != null){ t = t.getCause(); } return t; } public String getOrignalMessageKey() { return this.getOrignalException().getClass().getSimpleName(); } }