在@Around Aspect 中重新抛出异常

Re-throw an exception in @Around Aspect

在一些操作之后,rest controller 中从 around aspect 到 ExceptionHandler 的异常重新抛出是否正常,如下所示:

@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;
}

这是可行的,但我不知道是否出于某种原因我没有这样做。

建议(并非设计用于执行某些异常魔法)不应吞噬建议方法抛出的异常。

所以是的,如果您在 point.proceed() 周围有一个 try-catch,那么您应该重新抛出异常。

如果您不需要在方法执行(成功)后通知中完成的一些处理,您可以省略完整的异常处理。

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

如果您需要在建议调用之后完成一些处理,那么请使用 try-catch-finally bock。 catch 子句是可选的,但你必须重新抛出异常

 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
    }
 }