Spring AOP After throwing advice runs when a matched method execution exits by throwing an exception. Use @AfterThrowing annotation to declare a Spring After throwing advice. You can use this advice to perform any action after a method throws an exception.
Suppose you had to email and notify any team of critical method execution failure, you can use this advice.
@Aspect public class AfterThrowingExample { @Pointcut("execution(com.tedblob.controller.*.*(..))") public void controllerPointcut() { } @AfterThrowing("controllerPointcut()") public void doRecoveryActions() { // code if any exception happens in target method } }
Suppose you want the advice to run only when exceptions of a certain type are thrown or you want to access the thrown exception in the advice body. Then use the throwing attribute in both cases and bind the thrown exception to an advice parameter. The name used in the throwing attribute should match the parameter name of the advice method. When a method execution throws an exception, the exception will pass to the advice method as the corresponding argument value.
Let’s see an example to illustrate this.
@Aspect public class AfterThrowingExample { @AfterThrowing("execution(com.tedblob.controller.*.*(..))", throwing="ex") public void doRecoveryActions(NumberFormatException ex) { // ex contains the exception details } }
Here, the exception can bind to the advice parameter using the throwing attribute of the @AfterThrowing annotation and passing the exception in variable ex to the advice parameter. Since you restrict this advice to NumberFormatException exception, this advice will not execute if the target method throws other exceptions.
In this article, we have gone through the After Throwing advice and also restricting the advice using the exception type.