首页 > 解决方案 > Failsafe RetryPolicy - 从 supplyAsync 抛出异常

问题描述

我正在实施重试策略。基本上我想要做的是在单独的线程上重试 POST 请求。我正在使用 jhalterman 的故障安全(https://github.com/jhalterman/failsafe#asynchronous-api-integration)这是我的代码

Failsafe.with(retryPolicy).with(executor).future(() -> CompletableFuture.supplyAsync(() -> {
            try {
                CloseableHttpResponse response = client.execute(httpPost);
                httpPost.releaseConnection();
                client.close();
                return response;
            } catch (IOException e) {
                return null;
            }
        }).thenApplyAsync(response -> "Response: " + response)
          .thenAccept(System.out::println));

我不想在这里捕获 IOException。它由重试策略处理。目前重试不会发生,因为我在这里发现了异常。有没有办法从“supplyAsync”抛出异常,以便由重试策略处理?谢谢。谢谢

标签: javaasynchronouscompletable-futureretrypolicyjava-failsafe

解决方案


CompletionStage API 提供了几种不同的方式来处理和处理未经检查的异常。但在你的情况下,你得到的是一个 Checked 异常,你不走运。您要么必须处理它,要么将其向外扔给您的来电者。如果您更喜欢后一种方法,这是一种方法。

Failsafe.with(retryPolicy).with(executor).future(() -> CompletableFuture.supplyAsync(() -> {
            try {
                // Remainder omitted
                return response;
            } catch (IOException e) {
                throw new CompletionException(e);
            }
        }).thenApplyAsync(response -> "Response: " + response)
          .thenAccept(System.out::println));

推荐阅读