使用SpringAOP做自定义异常处理
1.自定义一个注解,该注解需要在各个项目的启动类上加上
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import({ExceptionHandle.class, ServiceAspect.class})
public @interface EnableExceptionAdvice {
}
2.自定义注解
![](https://i-blog.csdnimg.cn/blog_migrate/e5f496a75ccb24e012c1bb99f5c61c9b.png)
3.Spring的自定义异常处理
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8b850b1731f0daa5ccec55dfd2ab10a3.png)
4.自定义异常注解
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/733e32751d1e6aad2cfdd89d3932072c.png)
- 自定义的异常只可以抛RuntimeException
@Component
@Aspect
@Slf4j
public class ServiceAspect {
@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的环绕通知
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bfbd6ad2c210cda7b085cdc9960d55b1.png)
- 使用切面对Spring的Service注解进行切面
6.在其他项目的启动类中加入该注解
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/89c9201dde65a269f0ddd355a353f19f.png)