【问题标题】:Re-throw an exception in @Around Aspect [duplicate]在@Around Aspect 中重新抛出异常[重复]
【发布时间】:2016-07-04 21:35:29
【问题描述】:

在某些操作后重新抛出异常是否正常,从周围的方面到休息控制器中的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;
}

这是工作,但我不知道也许我出于某种原因没有这样做。

【问题讨论】:

  • 嗨,我的意思是使用 throw inside 方面的主要思想。

标签: java spring aop spring-aop


【解决方案1】:

建议(不是为执行某些异常魔术而设计的)不应吞下建议方法抛出的异常。

所以是的,如果你在 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 块。 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
    }
 }

【讨论】:

  • 请注意,如果在point.proceed() 之后的代码中抛出异常,则原始异常将丢失/屏蔽。新异常被捕获,当point.proceed() 中发生异常时指定运行的代码/操作将运行(可能是无意的)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多