使用SpringAOP來捕獲異常

當我們在開發程序的時候,經常遇到方法拋異常,而有時候異常打印出來的信息又不夠完整,這時候,可以通過AOP,自動在拋異常的時候將方法傳入的參數給打印出來。

實現步驟:

1.自定義註解作爲連接點(當然也可以用其他方式指定連接點,我覺得使用註解是個不錯的注意)

2.定義一個AOP切面

3.在需要捕獲異常的方法上面,添加註解

 

自定義註解

/**
 * 異常自動捕獲
 * 註解在方法上,當方法中拋出異常的時候,打印出方法以及方法的參數,方便排查
 * @see ExceptionCatchAop
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionCatch {
    /**
     * 如果沒有指定該值,則打印的方法名稱爲 '類名#方法名'
     * @return 自定義名稱
     */
    String value() default "";
}

定義切面,可以通過配置文件中指定exception.catch.switch=1/0,來打開或關閉異常捕獲功能

@Component
@Aspect
@ConditionalOnProperty(name = "exception.catch.switch", havingValue = "1")
public class ExceptionCatchAop {
    @Around("@annotation(exceptionCatch)")
    public Object around(ProceedingJoinPoint joinPoint, ExceptionCatch exceptionCatch) throws Throwable{
        try{
            return joinPoint.proceed();
        }catch (Throwable throwable){
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

            String value = exceptionCatch.value();
            if(StringUtils.isEmpty(value)){
                value = methodSignature.getMethod().getDeclaringClass().getName()+"#"+
                        methodSignature.getMethod().getName();
            }
            String[] paramterNames = methodSignature.getParameterNames();
            Object[] args = joinPoint.getArgs();
            StringBuilder sb = new StringBuilder();
            sb.append("【").append(value).append("】")
                .append("調用異常, 異常參數【");
            if(paramterNames.length>0){
                for(int i=0;i<paramterNames.length;i++){
                    sb.append(paramterNames[i]).append(" : ").append(args[i]);
                    if(i<paramterNames.length-1){
                        sb.append(",");
                    }
                }
            }
            sb.append("】");
            System.err.println(sb);
            throw throwable;
        }
    }
}

3.在需要的地方使用,添加上註解即可

效果

還可以指定方法的別名

效果

這樣,報錯的時候,就能看到方法傳入的參數,方便排查問題了

如果程序上線了,不需要異常捕獲了,再從配置文件中把開關關掉即可。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章