Vineel Pellella
Vineel Pellella

Reputation: 422

Cannot catch exception thrown in @Before advice in @AfterThrowing advice

I am using @Before and @AfterThrowing Spring AOP advices. In the before advice, I am validating data and throwing user-defined exceptions upon validation failure. As I already defined an @AfterThrowing, I am expecting this will catch the error to print additional information that I needed. But unexpectedly, I am not able to hit the @AfterThrowing advice. I am not sure whether I am doing it correctly or this is unsupported by Spring AOP.

Spring Configuration class

package configurations;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScans({
    @ComponentScan(value = "beans"), 
    @ComponentScan(value = "aspects")
})
@ComponentScan(basePackages = {"exceptions"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class SpringConfiguration {}

Employee class

package beans;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

@Component("employee")
//@DependsOn("fullName")
public class Employee implements Comparable<Employee>, Serializable, Cloneable {
    private int id;
    private String userId;
    private String email;
    
    @Autowired(required = false)
    private FullName fullName;
    
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getUserId() { return userId; }
    public void setUserId(String userId) { this.userId = userId; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
    public FullName getFullname() { return fullName; }
    public void setFullname(FullName fullname) { this.fullName = fullname; }
    
    @Override
    public String toString() {
        return "Employee [id=" + id + ", userId=" + userId + ", email=" + email + ", fullname=" + fullName + "]";
    }
    
    public int compareTo(Employee secondEmployee) {
        return Integer.compare(this.id, secondEmployee.id); 
    }
}

EmployeeAspects

package aspects;

import java.util.Arrays;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import exceptions.DataOverflowException;
import exceptions.NumberUnderflowException;

@Component
@Aspect
public class EmployeeAspect {
    
    @Before(value="execution(* beans.Employee.set*(..))")
    public void before(JoinPoint joinPoint) throws  Exception{
        List<Object> inputArguments = Arrays.asList(joinPoint.getArgs());
        for(Object argument : inputArguments) {
            switch(argument.getClass().getName()) {
                case "java.lang.String" : {
                    String inputString = (String) argument;
                    if(inputString.length() > 20) 
                        throw new DataOverflowException(joinPoint.getSignature().toString() +" is having excess input information to store.");
                    else
                        break;
                }
                case "java.lang.int" : {
                    int inputNumber = (int) argument;
                    if(inputNumber < 1) 
                        throw new NumberUnderflowException(joinPoint.getSignature().toString() +" is not meeting minimun input information to store.");
                    else
                        break;
                }
            }
        }
    }

    @Around("execution(* beans.Employee.*(..))")
    public void invoke(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Method with Signature :: "+ joinPoint.getSignature() + " having data "+ joinPoint.getTarget() + " invoked");
        joinPoint.proceed(joinPoint.getArgs());
        System.out.println("Method with Signature :: "+ joinPoint.getSignature() + " having data "+ joinPoint.getTarget() + " completed Successfully");
    }
    
    @AfterThrowing(pointcut = "execution(* *(..))",  throwing= "error")
    public void afterThrowing(JoinPoint joinPoint, Exception error) {
        System.out.println("===============ExceptionAspect============");
    }

}

TestClass

package clients;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import beans.Employee;
import configurations.SpringConfiguration;

public class TestClientA {
    public static void main(String[] args) {
        ConfigurableApplicationContext springContext = new AnnotationConfigApplicationContext(SpringConfiguration.class);
        Employee empl = springContext.getBean(Employee.class);
        empl.setEmail("[email protected]");
        springContext.close();
    }
}

Upvotes: 3

Views: 1662

Answers (1)

R.G
R.G

Reputation: 7131

From the reference documentation @AfterThrowing one can read:

Note that @AfterThrowing does not indicate a general exception handling callback. Specifically, an @AfterThrowing advice method is only supposed to receive exceptions from the join point (user-declared target method) itself but not from an accompanying @After/@AfterReturning method.

In your code the @Before advice executes before the actual user-declared target method and the exception is thrown. The control is returned from this point, and consequently, will not reach the @AfterThrowing advice

Also go through the advice ordering

As of Spring Framework 5.2.7, advice methods defined in the same @Aspect class that need to run at the same join point are assigned precedence based on their advice type in the following order, from highest to lowest precedence: @Around, @Before, @After, @AfterReturning, @AfterThrowing.

You may go through this answer (based on spring-aop-5.3.3) with @Around so that can try to implement your use-case.

Upvotes: 4

Related Questions