nova_rem
nova_rem

Reputation: 11

Aspect AOP not intercepting all methods within pointcut

I have created an aspect for the purpose of error logging and reporting within a microservices system but it is not intercepting all the methods that throw an exception within the pointcut.

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class LoggingAspect {
    @Pointcut("execution(* *(..)) && within(com.example..*)")
    public void triggerPointcut() {
        System.out.println("triggerPointcut");
    }
    

    @AfterThrowing(pointcut = "triggerPointcut()", throwing = "ex")
    public void logAfterThrowingAllMethods(JoinPoint joinPoint, Throwable ex) {
        System.out.println("****LoggingAspect.logAfterThrowingAllMethods() " + ex);
    }
}

For example, when I try to run a method that sends a message to a Kafka topic, a SerializationException occurs which I would like to account for, but the aspect is neither intercepting it nor logging it. I used @Around and @AfterThrowing, @Around has no advices and even though @AfterThrowing does have applicable advices, it still isn't covering everything. The target code below, which fails to be intercepted by the aspect, sits within the pointcut.

@Slf4j
    public class KafkaRunner implements Runnable{
        private final Consumer<String, Object> consumer;
    
        public Listener(Consumer<String, Object> consumer) {
            this.consumer = consumer;
        }
    
        public void start(){
            consumer.subscribe(Collections.singletonList("topic"));
            try{
                while(true){
                    ConsumerRecords<String, Object> records = consumer.poll(Duration.ofMillis(100));
                    for(ConsumerRecord<String, Object> record : records){
                        System.out.println("Received message: (" + record.key() + ", " + record.value() + ") at offset " + record.offset());
                    }
                }
            } catch (Exception e){
                System.out.println("Exception occurred: " + e);
            } finally {
                consumer.close();
            }
        
        }
    }

Upvotes: 1

Views: 93

Answers (0)

Related Questions