【问题标题】:Re-throw Throwable from inside callback从内部回调重新抛出 Throwable
【发布时间】:2014-08-16 00:47:07
【问题描述】:

我正在实现一个 AOP 拦截器,它处理 RetryTemplate 中的逻辑。问题是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 会触发代码样式违规。

【问题讨论】:

  • 不,你必须抓住并包装它。因为Throwable 没有在接口中声明。所以你不能忽视它。另外,您为什么不使用提供的RetryOperationsInterceptor 而是自己编写?
  • @M.Deinum 请发表您的评论作为答案,我会接受。感谢您指出 RetryOperationsInterceptor,我将尝试使用它,它与我实现的功能几乎相同,并以类似的方式处理 Throwable。

标签: java spring exception aspectj spring-aop


【解决方案1】:

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

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

虚拟类/接口:

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)

【讨论】:

    猜你喜欢
    • 2021-06-20
    • 2011-03-24
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 2014-05-11
    相关资源
    最近更新 更多