Joy
Joy

Reputation: 4473

Exception handling in @Around advice in Spring boot application

I have a use case as follows:

I have to do some preprocessing before the service layer is reached and do some further operations on preprocessed data. Basically, I would like to share the processed data between @Before and @AfterReturning's advice.

I have been going through various posts here, it seems the best way to achieve this with @Around, otherwise, I have to create a class-level attribute to capture the data between two different advices, and also, I have to handle thread-safety.

So resulting code snippet will look something like this:

    @Aspect
    public class MyAspect {
         
        @Pointcut("@within(org.springframework.stereotype.Service)")
        public void applicationServicePointcut() {
            
        }

        @Around(value = "applicationServicePointcut()")
        public Object process(ProceedingJoinPoint joinPoint) throws Throwable {
                //Before section
                ... some preprocessing...

                
                try {
                    Object result = joinPoint.proceed();
                    //After section
                     ...save preprocessed data in db...

                     return result;
                 } catch(Exception e) {
                     throw e;
                 }
        }
    }

But with @Around advice, I seem to have two questions/doubts:

  1. The code in the after section should be running only if there is no exception in service. With the above code structure, I guess, it should work fine. Please correct me, if I am wrong.

  2. One more aspect with higher precedence is defined to handle exceptions with @AfterThrowing advice. I am not able to understand, with this setting, will exception handling in the above code work fine?

    If it is not then, I guess I have to fall back to the option of defining two advices @Before and @AfterReturning in the aspect and share the data between these two with the help of the ThreadLocal variable.

Could anyone please help here? Thanks.

Upvotes: 0

Views: 1668

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36123

  1. The code in the after section should be running only if there is no exception in service. With the above code structure, I guess, it should work fine. Please correct me, if I am wrong.

This will work fine

  1. One more aspect with higher precedence is defined to handle exceptions with @AfterThrowing advice. I am not able to understand, with this setting, will exception handling in the above code work fine? If it is not then, I guess I have to fall back to the option of defining two advices @Before and @AfterReturning in the aspect and share the data between these two with the help of the ThreadLocal variable.

The question here is why do you catch exceptions when you don't do anything with it? You can remove the try/catch.

Upvotes: 1

Related Questions