6

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.

Alrail
  • 63
  • 1
  • 5

1 Answers1

8

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
    }
 }
Ralph
  • 118,862
  • 56
  • 287
  • 383
  • Be aware that if an exception is thrown in the code after `point.proceed()` the original exception will be lost/masked. The new exception is caught and the code/actions designated to run when an exception occurred in `point.proceed()` runs (probably unintentionally). – Matt Jul 16 '21 at 15:19