使用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.在需要的地方使用,添加上注解即可

效果

还可以指定方法的别名

效果

这样,报错的时候,就能看到方法传入的参数,方便排查问题了

如果程序上线了,不需要异常捕获了,再从配置文件中把开关关掉即可。

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