統一日志和異常管理配置好后,SSH項目中,代碼以往散落的log.info() 和 try..catch..finally 再也不見蹤影!
統一日志異常實現類:
- package com.pilelot.web.util;
- import org.apache.log4j.Logger;
- import org.springframework.aop.ThrowsAdvice;
- import org.springframework.dao.DataAccessException;
- import java.io.IOException;
- import java.lang.reflect.Method;
- import java.sql.SQLException;
- /**
- * 由Spring AOP調用 輸出異常信息,把程序異常拋向業務異常
- *
- * @author Andy Chan
- *
- */
- public class ExceptionAdvisor implements ThrowsAdvice
- {
- public void afterThrowing(Method method, Object[] args, Object target,
- Exception ex) throws Throwable
- {
- // 在后台中輸出錯誤異常異常信息,通過log4j輸出。
- Logger log = Logger.getLogger(target.getClass());
- log.info("**************************************************************");
- log.info("Error happened in class: " + target.getClass().getName());
- log.info("Error happened in method: " + method.getName());
- for (int i = 0; i < args.length; i++)
- {
- log.info("arg[" + i + "]: " + args[i]);
- }
- log.info("Exception class: " + ex.getClass().getName());
- log.info("ex.getMessage():" + ex.getMessage());
- ex.printStackTrace();
- log.info("**************************************************************");
- // 在這里判斷異常,根據不同的異常返回錯誤。
- if (ex.getClass().equals(DataAccessException.class))
- {
- ex.printStackTrace();
- throw new BusinessException("數據庫操作失敗!");
- } else if (ex.getClass().toString().equals(
- NullPointerException.class.toString()))
- {
- ex.printStackTrace();
- throw new BusinessException("調用了未經初始化的對象或者是不存在的對象!");
- } else if (ex.getClass().equals(IOException.class))
- {
- ex.printStackTrace();
- throw new BusinessException("IO異常!");
- } else if (ex.getClass().equals(ClassNotFoundException.class))
- {
- ex.printStackTrace();
- throw new BusinessException("指定的類不存在!");
- } else if (ex.getClass().equals(ArithmeticException.class))
- {
- ex.printStackTrace();
- throw new BusinessException("數學運算異常!");
- } else if (ex.getClass().equals(ArrayIndexOutOfBoundsException.class))
- {
- ex.printStackTrace();
- throw new BusinessException("數組下標越界!");
- } else if (ex.getClass().equals(IllegalArgumentException.class))
- {
- ex.printStackTrace();
- throw new BusinessException("方法的參數錯誤!");
- } else if (ex.getClass().equals(ClassCastException.class))
- {
- ex.printStackTrace();
- throw new BusinessException("類型強制轉換錯誤!");
- } else if (ex.getClass().equals(SecurityException.class))
- {
- ex.printStackTrace();
- throw new BusinessException("違背安全原則異常!");
- } else if (ex.getClass().equals(SQLException.class))
- {
- ex.printStackTrace();
- throw new BusinessException("操作數據庫異常!");
- } else if (ex.getClass().equals(NoSuchMethodError.class))
- {
- ex.printStackTrace();
- throw new BusinessException("方法末找到異常!");
- } else if (ex.getClass().equals(InternalError.class))
- {
- ex.printStackTrace();
- throw new BusinessException("Java虛擬機發生了內部錯誤");
- } else
- {
- ex.printStackTrace();
- throw new BusinessException("程序內部錯誤,操作失敗!" + ex.getMessage());
- }
- }
- }
自定義業務異常處理類 友好提示:
- package com.pilelot.web.util;
- /**
- * 自定義業務異常處理類 友好提示
- * @author Andy Chan
- *
- */
- public class BusinessException extends RuntimeException
- {
- private static final long serialVersionUID = 3152616724785436891L;
- public BusinessException(String frdMessage)
- {
- super(createFriendlyErrMsg(frdMessage));
- }
- public BusinessException(Throwable throwable)
- {
- super(throwable);
- }
- public BusinessException(Throwable throwable, String frdMessage)
- {
- super(throwable);
- }
- private static String createFriendlyErrMsg(String msgBody)
- {
- String prefixStr = "抱歉,";
- String suffixStr = " 請稍后再試或與管理員聯系!";
- StringBuffer friendlyErrMsg = new StringBuffer("");
- friendlyErrMsg.append(prefixStr);
- friendlyErrMsg.append(msgBody);
- friendlyErrMsg.append(suffixStr);
- return friendlyErrMsg.toString();
- }
- }
統一日志處理實現類:
- package com.pilelot.web.util;
- import org.aopalliance.intercept.MethodInterceptor;
- import org.aopalliance.intercept.MethodInvocation;
- import org.apache.log4j.Logger;
- /**
- * Spring 統一日志處理實現類
- * @author Andy Chan
- *
- */
- public class LogInterceptor implements MethodInterceptor
- {
- public Object invoke(MethodInvocation invocation) throws Throwable
- {
- Logger loger = Logger.getLogger(invocation.getClass());
- loger.info("--Log By Andy Chan -----------------------------------------------------------------------------");
- loger.info(invocation.getMethod() + ":BEGIN!--(Andy ChanLOG)");// 方法前的操作
- Object obj = invocation.proceed();// 執行需要Log的方法
- loger.info(invocation.getMethod() + ":END!--(Andy ChanLOG)");// 方法后的操作
- loger.info("-------------------------------------------------------------------------------------------------");
- return obj;
- }
- }
Spring配置文件添加:
- <!-- Spring 統一日志處理 LogInterceptor攔截器 配置 -->
- <bean id="logLnterceptor" class="com.pilelot.web.util.LogInterceptor"/>
- <!-- Spring 統一異常處理 ExceptionAdvisor配置 -->
- <bean id="exceptionHandler" class="com.pilelot.web.util.ExceptionAdvisor"></bean>
- <!-- Bean自動代理處理器 配置-->
- <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator" >
- <property name="beanNames">
- <list> <!-- 配置需要進行日志記錄的Service和Dao -->
- <value>commonDao</value>
- <!-- 配置所有Service結尾命名的Bean,即所有Service層的類都要經過exceptionHandler異常處理類 -->
- <value>*Service</value> <!-- Service層的Bean ID 命名要以Service結尾 -->
- </list>
- </property>
- <property name="interceptorNames">
- <list>
- <value>exceptionHandler</value>
- <value>logLnterceptor</value>
- <!--<value>transactionInterceptor</value>-->
- </list>
- </property>
- </bean>
- lt;!-- ——————————————————Spring 統一日志處理 + 統一異常處理 配置結束—————————————悲傷的分隔線—————————— -->
這樣簡單三步,就實現了由Spring統一日志+統一異常管理,代碼清爽了不少!