在系統開發過程中,出現錯誤在所難免。雖然系統出錯時控制檯也會報錯,但是因爲系統控制檯輸出太多,往往不能快速定位出現錯誤的功能點及原因。在此通過使用註解,結合spring的AOP,來製作一個錯誤輸出攔截器。
首先寫一個註解類Catcher:
@Target({ ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface Catcher { String name();//模塊名 }
然後定義一個切面:ExceptionInterceptor
@Aspect public class ExceptionInterceptor { private Logger logger = Logger.getLogger(ExceptionInterceptor.class); /** * 攔截service層帶有Catcher註解的所有異常 * @param point * @param cat * @param ex */ @AfterThrowing(pointcut="execution(* com.*.service.*.*(..))&&@annotation(cat)",throwing="ex") public void serviceSite(JoinPoint point,Catcher cat,Throwable ex){ StackTraceElement st=ex.getStackTrace()[0]; logger.error("產生錯誤的模塊:"+cat.name()); logger.error("產生錯誤的類:"+point.getTarget().getClass().getSimpleName()); logger.error("產生異常的方法:"+point.getSignature().getName()); logger.error("出錯行數:"+st.getLineNumber()); logger.error("異常類型:"+ex.getClass().getName()); logger.error("錯誤信息:"+ex.getMessage()); } }
注:ExceptionInterceptor需要在spring.xml中定義
<bean id="exceptionInterceptor" class="com.util.ExceptionInterceptor"> <property name="sessionFactory" ref="sessionFactory" /> </bean>
用法:
因爲在攔截器中攔截的是service層的方法(當然也可以攔截其它地方),所以對於需要攔截的方法,都要加上@Catcher註解。
@Catcher(name="需要捕獲錯誤的模塊") public void test(){ throw new RuntimeException("此模塊拋出異常"); }
運行這個方法時,系統就會報錯:
產生錯誤的類:類名
產生異常的方法:test 出錯行數:相應的行數 異常類型:RuntimeException 錯誤信息:出現了一個錯誤
是不是很直觀呢?