从回调中重新抛出Throwable

时间:2014-06-25 12:39:55

标签: java spring exception-handling aspectj

我正在实现一个处理RetryTemplate中逻辑的AOP拦截器。问题是ProceedingJoinPoint#execute被声明为抛出Throwable,但RetryTemplate#doWithRetry只允许重新抛出Exception。所以我必须包裹Throwable,然后将其打开。

我最好的尝试看起来像这样:

@Aspect
@Component
public class RetryableOperationFailureInterceptor {

    @Around("@annotation(retryable)")
    public Object performOperation(final ProceedingJoinPoint pjp, Retryable retryable)
            throws Throwable {

        RetryTemplate retryTemplate = getRetryTemplate(retryable);
        try {
            return retryTemplate.execute(new RetryCallback<Object>() {
                @Override
                public Object doWithRetry(RetryContext context)
                        throws Exception {

                    try {
                        return pjp.proceed(); // throws Throwable
                    } catch (Exception e) {
                        throw e;
                    } catch (Error e) {
                        throw e;
                    } catch (Throwable e) {
                        throw new RetryWrappedException(e);
                    }
                }
            });
        } catch (RetryWrappedException e) {
            throw e.getCause();
        }
    }
}

有没有办法避免包装或/和捕捉Throwable?最新的对我来说更重要,因为捕获Throwable会触发代码样式违规。

1 个答案:

答案 0 :(得分:0)

微米。 Deinum是对的,但您不需要使用自己的RetryWrappedException,因为AspectJ已经提供SoftException(扩展RuntimeException)来软化/包装已检查的异常,但它也适用于其他{ {1}}秒。

因为我发现您的问题很有趣,但我不是Spring用户,所以我将您的一些示例类复制为假人或最小实现,以便创建一个完全正常的POJO + AspectJ示例,而不需要任何Spring依赖。我还扩展了around建议,以便自己进行重试循环,从Throwable注释中读取maxRetries值。我知道这不是100%的用例,但它说明了问题和其他一些事情:

虚拟课程/界面:

Retryable

-

package de.scrum_master.app;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Retryable {
    int maxRetries();
}

-

package de.scrum_master.app;

public class RetryContext {}

-

package de.scrum_master.app;

public interface RetryCallback<T> {
    Object doWithRetry(RetryContext context) throws Exception;
}

驱动程序应用程序:

package de.scrum_master.app;

public class RetryTemplate {
    public Object execute(RetryCallback<Object> retryCallback) throws Exception {
        return retryCallback.doWithRetry(new RetryContext());
    }
}

如果没有方面,则不会重试,package de.scrum_master.app; import java.util.Random; public class Application { private static final Random RANDOM = new Random(); public static void main(String[] args) throws Exception { new Application().performOperation(); } @Retryable(maxRetries = 2) public void performOperation() throws Exception { System.out.println("Performing some operation"); if (RANDOM.nextBoolean()) throw new Exception("Operation failed"); System.out.println("Operation succeeded"); } } 会随机成功

performOperation()

或失败

Performing some operation
Operation succeeded

拦截/重试方面:

现在我们可以通过以下方面

  • Performing some operationException in thread "main" java.lang.Exception: Operation failed at de.scrum_master.app.Application.performOperation(Application.java:16) at de.scrum_master.app.Application.main(Application.java:9) 注释的拦截方法,
  • 获取最大重试次数和
  • 循环并尝试通过Retryable执行连接点执行次数(proceed(),因为即使请求零重试,我们也至少调用一次方法)。

正如您所看到的,我们根据错误类型使用不同的错误处理:

  • 如果尚未达到最大重试次数,则只打印maxRetries + 1,否则重新抛出Exception,即如果最终重试也失败,则抛出异常。
  • 将始终重新抛出错误,因为JVM通常会抛出错误并且不可恢复,即在这种情况下将不再重试。
  • Throwable(绝不会发生)将被包裹在SoftException中,后者会被重新抛出。
package de.scrum_master.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.SoftException;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

import de.scrum_master.app.RetryCallback;
import de.scrum_master.app.RetryContext;
import de.scrum_master.app.RetryTemplate;
import de.scrum_master.app.Retryable;

@Aspect
public class RetryableOperationFailureInterceptor {
    @Around("@annotation(retryable) && execution(* *(..))")
    public Object performOperation(final ProceedingJoinPoint pjp, final Retryable retryable) throws Throwable {
        final int maxRetries = retryable.maxRetries();
        System.out.println(pjp + " - maxRetries = " + maxRetries);
        RetryTemplate retryTemplate = getRetryTemplate(retryable);
        return retryTemplate.execute(
            new RetryCallback<Object>() {
                @Override
                public Object doWithRetry(RetryContext context) throws Exception {
                    for (int i = 0; i <= maxRetries; i++) {
                        System.out.println("Retry #" + i);
                        try {
                            return pjp.proceed();
                        } catch (Exception e) {
                            if (i == maxRetries)
                                throw e;
                            System.out.println(e);
                        } catch (Error e) {
                            throw e;
                        } catch (Throwable t) {
                            throw new SoftException(t);
                        }
                    }
                    return null;
                }
            }
        );
    }

    private RetryTemplate getRetryTemplate(Retryable retryable) {
        return new RetryTemplate();
    }
}

带有有效Aspect的结果输出:

立即成功(无需重试):

execution(void de.scrum_master.app.Application.performOperation()) - maxRetries = 2
Retry #0
Performing some operation
Operation succeeded

重试后成功:

execution(void de.scrum_master.app.Application.performOperation()) - maxRetries = 2
Retry #0
Performing some operation
java.lang.Exception: Operation failed
Retry #1
Performing some operation
java.lang.Exception: Operation failed
Retry #2
Performing some operation
Operation succeeded

最终重试后失败:

execution(void de.scrum_master.app.Application.performOperation()) - maxRetries = 2
Retry #0
Performing some operation
java.lang.Exception: Operation failed
Retry #1
Performing some operation
java.lang.Exception: Operation failed
Retry #2
Performing some operation
Exception in thread "main" java.lang.Exception: Operation failed
    at de.scrum_master.app.Application.performOperation_aroundBody0(Application.java:16)
    at de.scrum_master.app.Application$AjcClosure1.run(Application.java:1)
    at org.aspectj.runtime.reflect.JoinPointImpl.proceed(JoinPointImpl.java:149)
    at de.scrum_master.aspect.RetryableOperationFailureInterceptor$1.doWithRetry(RetryableOperationFailureInterceptor.java:27)
    at de.scrum_master.app.RetryTemplate.execute(RetryTemplate.java:5)
    at de.scrum_master.aspect.RetryableOperationFailureInterceptor.performOperation(RetryableOperationFailureInterceptor.java:20)
    at de.scrum_master.app.Application.performOperation(Application.java:13)
    at de.scrum_master.app.Application.main(Application.java:9)