gpt4 book ai didi

java - PlayWS - 当请求超时时如何抛出异常?

转载 作者:行者123 更新时间:2023-12-02 10:37:01 25 4
gpt4 key购买 nike

使用 PlayWS 执行长时间下载时,它使用 CompletableFuture ,这些有时会达到定义的请求超时。当发生这种情况时,PlayWS 似乎不会抛出异常(至少在我的配置中),因此下载不能被标记为失败,并且尽管数据已损坏,但仍会进行处理。

请原谅这段令人厌恶的代码:

final CompletionStage<WSResponse> futureResponse = this.playWS.client
.url(importSource.getDownloadUrl())
.setMethod(HttpMethod.GET)
.setRequestTimeout(Duration.ofSeconds(5)) // When the timeout is reached, the download gets canceled
.stream();

try {
futureResponse
.thenAccept(res -> {
try (OutputStream outputStream = Files.newOutputStream(file.toPath())) {
final Source<ByteString, ?> responseBody = res.getBodyAsSource();
final Sink<ByteString, CompletionStage<Done>> outputWriter =
Sink.foreach(bytes -> {
outputStream.write(bytes.toArray());
});
responseBody
.runWith(outputWriter, this.playWS.materializer)
.whenComplete((value, error) -> {
System.out.println("VALUE: "+value); // == "Done"
System.out.println("Error: "+error); // == null
})
.exceptionally(exception -> {
throw new IllegalStateException("Download failed for: " + importSource.getDownloadUrl(), exception);
})
.toCompletableFuture().join();
} catch (final IOException e) {
throw new IllegalStateException("Couldn't open or write to OutputStream.", e);
}
})
.exceptionally(exception -> {
throw new IllegalStateException("Download failed for: " + importSource.getDownloadUrl(), exception);
})
.toCompletableFuture().get();
} catch (InterruptedException | ExecutionException e) {
throw new IllegalStateException("Couldn't complete CompletableFuture.", e);
}

我是在做一些根本性错误的事情还是这是一个错误?

我看到的唯一解决方案是:

  1. 计算接收到的字节数并将其与 Content-Length header 进行比较.
  2. 将请求超时设置为 -1(无限期)。

感谢您的任何建议。

最佳答案

我认为有些过于复杂了。

您只需从 FutureCompletableStage 附加到 Source。 Akka Streams 拥有比 CompletableFuture 更强大的 API(我的观点)

final CompletionStage<WSResponse> futureResponse = this.playWS.client
.url(importSource.getDownloadUrl())
.setMethod(HttpMethod.GET)
.setRequestTimeout(Duration.ofSeconds(5))
.stream();

Source<WSResponse> source = Source.fromCompletableStage(futureResponse);
source.map(...).filter(...).recover(...).runforeach(..., playWS.materializer)

关于java - PlayWS - 当请求超时时如何抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53203211/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com