Search code examples
javaspringaopspring-aop

Re-throw an exception in @Around Aspect


Is it normal to re-throw, after some action, an exception from around aspect to ExceptionHandler in rest controller, like this:

@Around("execution(* *(..)) && @annotation(someAnnotation)")
public Object catchMethod(ProceedingJoinPoint point, SomeAnnotation someAnnotation) throws Throwable {
  //some action
    try {
        result = point.proceed();
    } catch (Exception e) {
        //some action
        throw e; //can I do this?
    }
     //some action
    return result;
}

It's work but I don't know maybe I haven't to do this for some reason.


Solution

  • An advice (that is not designed to do some exception magic) should not swallow an exception that is thrown by the adviced method.

    So yes, if you have a try-catch around point.proceed() then you should rethrow the exception.

    If you do not need some handling that is done in the advice after the method is executed (successfully) you can omit the complete exception handling.

     @Around("execution(* *(..)) && @annotation(someAnnotation)")
     public Object catchMethod(ProceedingJoinPoint point, SomeAnnotation someAnnotation) throws Throwable {
        //some action
        return point.proceed();
     }
    

    If you need some handing that is done after the advice invocation, then use a try-catch-finally bock. The catch clause is optional, but you have to rethrow the exception

     public Object catchMethod(ProceedingJoinPoint point, SomeAnnotation someAnnotation) throws Throwable {        
        //some action
        try {
           Result result = point.proceed();
           //some action that are executed only if there is no exception
        }  catch (Exception e) {
           //some action that are executed only if there is an exception
           throw e; //!!
        } finally {
           //some action that is always executed
        }
     }