Video in progress

Strong Junior 🌱 Spring

What happens in an @Around advice if proceed() is not called, or its result is not returned?

If proceed() isn't called, the original method doesn't run at all. If it's called but the result isn't returned, the caller gets null; for a method returning a primitive, AopInvocationException. In both cases the system silently misbehaves.

📖 Answer

This aspect was meant to "only write a log":

@Around("execution(* uz.shop.service.*.*(..))")
Object log(ProceedingJoinPoint pjp) throws Throwable {
    log.info("-> {}", pjp.getSignature());
    pjp.proceed();                 // the result is thrown away
    return null;                   // mistake!
}

What happens:

  • List<Order> findAll(): the caller gets null and an NPE later;
  • int count(): AopInvocationException: Null return value from advice does not match primitive return type;
  • void methods keep working, which is why the mistake isn't noticed right away.

If there's no proceed() at all, the business logic doesn't run and there's no exception either. For example, the log says the payment was "transferred" when nothing actually happened.

The right way:

@Around("...")
Object log(ProceedingJoinPoint pjp) throws Throwable {
    log.info("-> {}", pjp.getSignature());
    try {
        return pjp.proceed();
    } catch (Throwable t) {
        log.warn("xato: {}", t.getMessage());
        throw t;                    // we don't swallow the exception
    }
}

Another trap is catching the exception and not rethrowing it. Then @Transactional doesn't roll back and the caller thinks it succeeded. If you don't need @Around, @Before/@AfterReturning are safer.