使用SpringAOP做自定义异常处理

使用SpringAOP做自定义异常处理

1.自定义一个注解,该注解需要在各个项目的启动类上加上

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import({ExceptionHandle.class, ServiceAspect.class})
public @interface EnableExceptionAdvice {

}

2.自定义注解

3.Spring的自定义异常处理

在这里插入图片描述

4.自定义异常注解

在这里插入图片描述

  1. 自定义的异常只可以抛RuntimeException
@Component
@Aspect
@Slf4j
public class ServiceAspect {
    //修改一下对方法的检测,这样也可以检测使用了MybatisPlus的IService注解的类的所有方法,+代表实现类
    @Around("within(@org.springframework.stereotype.Service *) || within(com.baomidou.mybatisplus.extension.service.IService+)")
    public Object handleExceptionLog(ProceedingJoinPoint pj){
        try {
            //执行方法前进行一次调用
            long beforeMethod = System.currentTimeMillis();
            log.debug("{}方法执行了,在{}时间执行了",pj.getSignature().getName(),beforeMethod);
            log.debug("{}方法执行了,参数:{}",pj.getSignature().getName(), Arrays.asList(pj.getArgs()));
            //执行方法
            Object result = pj.proceed();
            //正常执行方法后检测一次
            log.debug("{}方法执行成功了,耗时{}秒",pj.getSignature().getName(),System.currentTimeMillis()-beforeMethod);
            return result;
        } catch (Throwable throwable) {
            //抛异常进行检测
            log.error("{}方法执行失败,原因:{}",pj.getSignature().getName(),throwable.getMessage(),throwable );
            //对这个异常进行判断
            if (throwable instanceof LyException){
                throw (LyException)throwable;
            }
            throw new LyException(500,throwable );
        }
    }
}

5.AOP的环绕通知

在这里插入图片描述

  1. 使用切面对Spring的Service注解进行切面

6.在其他项目的启动类中加入该注解

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值