本文整理匯總了Java中java.util.concurrent.CompletionStage.handle方法的典型用法代碼示例。如果您正苦於以下問題:Java CompletionStage.handle方法的具體用法?Java CompletionStage.handle怎麽用?Java CompletionStage.handle使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類java.util.concurrent.CompletionStage
的用法示例。
在下文中一共展示了CompletionStage.handle方法的4個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: catchException
import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
/**
* Returns a wrapper of {@code stage} that if {@code stage} failed with exception of
* {@code exceptionType}, that exception is caught and wrapped inside a {@link Maybe} to complete
* the wrapper stage normally.
*
* <p>This is useful if the asynchronous code is interested in recovering from its own exception
* without having to deal with other exception types.
*/
public static <T, E extends Throwable> CompletionStage<Maybe<T, E>> catchException(
Class<E> exceptionType, CompletionStage<? extends T> stage) {
requireNonNull(exceptionType);
CompletableFuture<Maybe<T, E>> future = new CompletableFuture<>();
stage.handle((v, e) -> {
try {
if (e == null) {
future.complete(Maybe.of(v));
} else {
unwrapFutureException(exceptionType, e)
.map(cause -> future.complete(Maybe.except(cause)))
.orElseGet(() -> future.completeExceptionally(e));
}
} catch (Throwable x) { // Just in case there was a bug. Don't hang the thread.
if (x != e) x.addSuppressed(e);
future.completeExceptionally(x);
}
return null;
});
return future;
}
示例2: pingAsync
import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
public CompletionStage<Status> pingAsync() {
WSRequest request = wsClient.url(storageAdapterWebserviceUrl + "/status");
request.setRequestTimeout(Duration.ofSeconds(10));
CompletionStage<WSResponse> responsePromise = request.get();
return responsePromise.handle((result, error) -> {
if (error != null) {
return new Status(false, error.getMessage());
} else {
if (result.getStatus() == 200) {
return new Status(true, "Alive and well");
} else {
return new Status(false, result.getStatusText());
}
}
});
}
示例3: naiveExceptionHandlingCode
import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
private static <T> CompletionStage<T> naiveExceptionHandlingCode(
CompletionStage<T> stage) {
return stage.handle((v, e) -> {
assertThat(e).isInstanceOf(MyException.class);
return null;
});
}
示例4: toCompletableFuture
import java.util.concurrent.CompletionStage; //導入方法依賴的package包/類
/** Demo utility method for external reliable toCompletableFuture */
static <T> CompletableFuture<T> toCompletableFuture(CompletionStage<T> stage) {
CompletableFuture<T> f = new CompletableFuture<>();
stage.handle((T t, Throwable ex) -> {
if (ex != null) f.completeExceptionally(ex);
else f.complete(t);
return null;
});
return f;
}