在@Around Aspect中重新抛出异常

时间:2016-03-18 08:07:08

标签: java spring aop spring-aop

在某些操作之后,从静止控制器中的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;
}

这是有效的,但我不知道也许我出于某种原因不能这样做。

1 个答案:

答案 0 :(得分:4)

建议(不是为了做一些异常魔法)不应该吞下建议方法抛出的异常。

所以是的,如果你在point.proceed()附近试一试,那么你应该重新抛出异常。

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

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