@Around: 需要代理的方法执行在其中,只有异常才会被@AfterThrowing捕获
1.1 使用场景
因为dubbo接口的异常,nodeJS中无法拿到返回值,ReponseData对象只在provider层进行封装。因此需要基于切面捕获异常,封装成ResponseData对象
package com.showjoy.activity.aspect;
import com.showjoy.activity.api.result.ResponseData;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class ActivityAnchorAspect {
private static Logger logger = LoggerFactory.getLogger(ProviderExceptionAspect.class);
@Pointcut("execution(* com.showjoy..*.provider..*.*(..))")
public void pointCut() {
System.out.println("@PointCut 定义一个切入点");
}
@Around("pointCut()")
public Object handlerException(ProceedingJoinPoint point) {
ResponseData result ;
try {
Object object = point.proceed();
System.out.println("@Around要代理的方法执行在其中, 若不用@Around只有异常情况下才会被@AfterThrowing捕获");
return object;
}catch (Throwable e){
logger.error(point.getSignature() + " error ", e);
return new ResponseData(false).setMsg(e.getMessage());
}
}
@Before("pointCut()")
public void permissionCheck(JoinPoint point) {
System.out.println("@Before 在目标对象执行之前执行");
}
@AfterReturning(pointcut = "pointCut()", returning = "returnValue")
public void log(JoinPoint point, Object returnValue) {
System.out.println("无异常情况下,@AfterReturning 在@After后执行;且有返回值的情况下都会执行");
}
@After("pointCut()")
public void releaseResource(JoinPoint point) {
System.out.println("无异常情况下,@After在@AfterRunning前执行");
}
@AfterThrowing("pointCut()")
public void releaseResourceThrow(JoinPoint point) {
System.out.println("@AfterThrowing无异常情况下不执行");
}
}