使用SpringAOP做自定义异常处理
1.自定义一个注解,该注解需要在各个项目的启动类上加上
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import({ExceptionHandle.class, ServiceAspect.class})
public @interface EnableExceptionAdvice {
}
2.自定义注解
3.Spring的自定义异常处理
4.自定义异常注解
- 自定义的异常只可以抛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的环绕通知
- 使用切面对Spring的Service注解进行切面
6.在其他项目的启动类中加入该注解