我想以异步方式使用Java Http Client:java.net.http.HttpClient
。当我收到http响应(任何http代码)或超时时,我想执行一些自定义Java代码。我很难完成错误处理的主体。
CompletableFuture<HttpResponse<String>> response =
httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApplyAsync(body -> {
System.out.println("Request finished");
return body;
})
.exceptionallyAsync(exception -> {
// WHAT TO RETURN HERE ?
});
方法:exceptionallyAsync
返回:CompletableFuture<T>
,但是我不知道如何完成这个方法。
你能帮我完成这个方法吗?我无法在GitHub或Google中找到示例。
可以使用
.exceptionally(this::handlError)
如果this
是您的响应处理程序,使用如下方法:
private Void handlError(Throwable ex) {
System.out.println(ex.toString());
return null;
}