JAVA aop @AfterThrowing 无法捕获异常
JAVA aop @AfterThrowing couldn't catch Exception
我想在这个方法出现异常时做一些动作。
因此,我制作了 AfterReturning、AfterThrowing 等 aop 函数...
我故意更改了引发异常的方法。
但是请求到达AfterReturning,即使发生异常也不是AfterThrowing。
如何让这个请求到达 AfterThrowing 方法?
@EventListener
@GetHost
public void getHost(ContextRefreshedEvent event) throws Exception {
try {
prHostName = InetAddress.getLocalHost().getHostName();
prIpAddr = InetAddress.getLocalHost().getHostAddress();
//making exception on purpose
String[] tmp = new String[0];
prIpAddr = tmp[1];
} catch (Exception exception) {
prHostName = "unknown";
prIpAddr = "unknown";
System.out.println("unknown");
exception.printStackTrace();
}
}
有aop方法
@Pointcut("@annotation(com.etc.web.annotation.GetHost)")
public void componentMethod() {}
@Before("componentMethod()")
public void beforeComponent(JoinPoint point) {
System.out.println("beforeComponent");
}
@Around("componentMethod()")
public Object aroundComponent(ProceedingJoinPoint point) throws Throwable {
System.out.println("aroundComponent");
Object retVal = point.proceed();
return retVal;
}
@AfterReturning(pointcut = "componentMethod()", returning = "result")
public void afterComponent(JoinPoint point, Object result) {
System.out.println("afterReturnComponent");
}
@AfterThrowing(pointcut = "componentMethod()", throwing = "exception")
public void afterThrowingComponent(JoinPoint point, Throwable exception) throws Exception {
System.out.println("afterThrowingComponent");
}
请帮助我。
谢谢!
方法没有异常退出,因为异常被捕获,方法正常退出。所以当然不会触发@AfterThrowing
。这不应该让你感到惊讶。
我想在这个方法出现异常时做一些动作。 因此,我制作了 AfterReturning、AfterThrowing 等 aop 函数...
我故意更改了引发异常的方法。 但是请求到达AfterReturning,即使发生异常也不是AfterThrowing。
如何让这个请求到达 AfterThrowing 方法?
@EventListener
@GetHost
public void getHost(ContextRefreshedEvent event) throws Exception {
try {
prHostName = InetAddress.getLocalHost().getHostName();
prIpAddr = InetAddress.getLocalHost().getHostAddress();
//making exception on purpose
String[] tmp = new String[0];
prIpAddr = tmp[1];
} catch (Exception exception) {
prHostName = "unknown";
prIpAddr = "unknown";
System.out.println("unknown");
exception.printStackTrace();
}
}
有aop方法
@Pointcut("@annotation(com.etc.web.annotation.GetHost)")
public void componentMethod() {}
@Before("componentMethod()")
public void beforeComponent(JoinPoint point) {
System.out.println("beforeComponent");
}
@Around("componentMethod()")
public Object aroundComponent(ProceedingJoinPoint point) throws Throwable {
System.out.println("aroundComponent");
Object retVal = point.proceed();
return retVal;
}
@AfterReturning(pointcut = "componentMethod()", returning = "result")
public void afterComponent(JoinPoint point, Object result) {
System.out.println("afterReturnComponent");
}
@AfterThrowing(pointcut = "componentMethod()", throwing = "exception")
public void afterThrowingComponent(JoinPoint point, Throwable exception) throws Exception {
System.out.println("afterThrowingComponent");
}
请帮助我。 谢谢!
方法没有异常退出,因为异常被捕获,方法正常退出。所以当然不会触发@AfterThrowing
。这不应该让你感到惊讶。