Java Code Examples for java.util.concurrent.CompletionStage#exceptionally()
The following examples show how to use
java.util.concurrent.CompletionStage#exceptionally() .
These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: servicetalk File: CompletableToCompletionStageTest.java License: Apache License 2.0 | 6 votes |
private void verifyError(boolean errorBeforeListen) throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); AtomicReference<Throwable> causeRef = new AtomicReference<>(); CompletionStage<Void> stage = source.toCompletionStage(); if (errorBeforeListen) { source.onError(DELIBERATE_EXCEPTION); stage.exceptionally(cause -> { causeRef.compareAndSet(null, cause); latch.countDown(); return null; }); } else { stage.exceptionally(cause -> { causeRef.compareAndSet(null, cause); latch.countDown(); return null; }); source.onError(DELIBERATE_EXCEPTION); } latch.await(); assertSame(DELIBERATE_EXCEPTION, causeRef.get()); }
Example 2
Source Project: curator File: AsyncExamples.java License: Apache License 2.0 | 6 votes |
private static void handleWatchedStage(CompletionStage<WatchedEvent> watchedStage) { // async handling of Watchers is complicated because watchers can trigger multiple times // and CompletionStage don't support this behavior // thenAccept() handles normal watcher triggering. watchedStage.thenAccept(event -> { System.out.println(event.getType()); System.out.println(event); // etc. }); // exceptionally is called if there is a connection problem in which case // watchers trigger to signal the connection problem. "reset()" must be called // to reset the watched stage watchedStage.exceptionally(exception -> { AsyncEventException asyncEx = (AsyncEventException)exception; asyncEx.printStackTrace(); // handle the error as needed handleWatchedStage(asyncEx.reset()); return null; }); }
Example 3
Source Project: servicetalk File: PublisherToCompletionStageTest.java License: Apache License 2.0 | 5 votes |
private void verifyError(boolean completeBeforeListen, boolean sendData) throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); AtomicReference<Throwable> resultRef = new AtomicReference<>(); CompletionStage<? extends Collection<String>> stage = publisher.toCompletionStage(); if (completeBeforeListen) { if (sendData) { publisher.onNext("Hello", "World"); } publisher.onError(DELIBERATE_EXCEPTION); stage.exceptionally(cause -> { resultRef.compareAndSet(null, cause); latch.countDown(); return null; }); } else { stage.exceptionally(cause -> { resultRef.compareAndSet(null, cause); latch.countDown(); return null; }); if (sendData) { publisher.onNext("Hello", "World"); } publisher.onError(DELIBERATE_EXCEPTION); } latch.await(); assertThat(resultRef.get(), is(DELIBERATE_EXCEPTION)); }
Example 4
Source Project: teku File: SafeFuture.java License: Apache License 2.0 | 5 votes |
public static void reportExceptions(final CompletionStage<?> future) { future.exceptionally( error -> { final Thread currentThread = Thread.currentThread(); currentThread.getUncaughtExceptionHandler().uncaughtException(currentThread, error); return null; }); }
Example 5
Source Project: pgadba File: PgSession.java License: BSD 2-Clause "Simplified" License | 5 votes |
protected CompletionStage<Object> attachErrorHandler(CompletionStage<Object> result) { if (errorHandler != null) { return result.exceptionally(t -> { Throwable ex = unwrapException(t); errorHandler.accept(ex); if (ex instanceof SqlSkippedException) { throw (SqlSkippedException) ex; } else { throw new SqlSkippedException("TODO", ex, null, -1, null, -1); } }); } else { return result; } }
Example 6
Source Project: mug File: Utils.java License: Apache License 2.0 | 5 votes |
static CompletionStage<?> ifCancelled( CompletionStage<?> stage, Consumer<? super CancellationException> action) { requireNonNull(action); return stage.exceptionally(e -> { cast(e, CancellationException.class).ifPresent(action); return null; }); }
Example 7
Source Project: mug File: MaybeTest.java License: Apache License 2.0 | 5 votes |
private static <T> CompletionStage<T> naiveExceptionallyCode( CompletionStage<T> stage) { return stage.exceptionally(e -> { assertThat(e).isInstanceOf(MyException.class); return null; }); }
Example 8
Source Project: lams File: CompletionStageReturnValueHandler.java License: GNU General Public License v2.0 | 5 votes |
@Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { mavContainer.setRequestHandled(true); return; } final DeferredResult<Object> deferredResult = new DeferredResult<Object>(); WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer); @SuppressWarnings("unchecked") CompletionStage<Object> future = (CompletionStage<Object>) returnValue; future.thenAccept(new Consumer<Object>() { @Override public void accept(Object result) { deferredResult.setResult(result); } }); future.exceptionally(new Function<Throwable, Object>() { @Override public Object apply(Throwable ex) { deferredResult.setErrorResult(ex); return null; } }); }
Example 9
Source Project: spring4-understanding File: CompletionStageReturnValueHandler.java License: Apache License 2.0 | 5 votes |
@Override public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception { if (returnValue == null) { mavContainer.setRequestHandled(true); return; } final DeferredResult<Object> deferredResult = new DeferredResult<Object>(); WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer); @SuppressWarnings("unchecked") CompletionStage<Object> future = (CompletionStage<Object>) returnValue; future.thenAccept(new Consumer<Object>() { @Override public void accept(Object result) { deferredResult.setResult(result); } }); future.exceptionally(new Function<Throwable, Object>() { @Override public Object apply(Throwable ex) { deferredResult.setErrorResult(ex); return null; } }); }
Example 10
Source Project: docker-nginx-consul File: Boot.java License: MIT License | 5 votes |
public static void main(String[] args) { // config final String appId = UUID.randomUUID().toString(); final AppConfiguration appConfig = AppConfiguration.loadConfig(appId); // actor system init final ActorSystem system = ActorSystem.create(); final Materializer materializer = ActorMaterializer.create(system); // service discovery actor final ActorRef serviceDiscoveryActor = system.actorOf(DiscoveryAgentActor.props(appConfig), "example-app-consul-service"); // http init final Flow<HttpRequest, HttpResponse, NotUsed> routeFlow = new AppResource(appConfig).routes().flow(system, materializer); final CompletionStage<ServerBinding> binding = Http .get(system) .bindAndHandle( routeFlow, ConnectHttp.toHost(appConfig.host, appConfig.port), materializer ); // exception handling binding.exceptionally(failure -> { System.err.println("Something very bad happened! " + failure.getMessage()); system.terminate(); return null; }); }
Example 11
Source Project: java-async-util File: FlowAdapter.java License: Apache License 2.0 | 4 votes |
/** * Supply the subscriber with n elements, closing the iterator if iteration ends or throws. * Should be called under {@code lock}. * * @param n number of elements * @return when we're finished fetching elements */ private CompletionStage<Void> getn(final long n) { CompletionStage<Void> fillStage; if (n <= 0) { fillStage = StageSupport.exceptionalStage( new IllegalArgumentException("subscription requests must be positive")); } else { fillStage = AsyncTrampoline.asyncWhile(new Supplier<>() { long demand = n; @Override public CompletionStage<Boolean> get() { if (this.demand-- == 0 || IteratorBackedSubscription.this.finished.get()) { return StageSupport.completedStage(false); } return IteratorBackedSubscription.this.iterator .nextStage() .thenCompose(e -> e.fold(this::onEnd, this::onNext)); } private CompletionStage<Boolean> onEnd(final AsyncIterator.End end) { if (finish()) { return IteratorBackedSubscription.this.iterator.close() .handle((ig, closeEx) -> { notifySubscriber(false, null, closeEx); return false; }); } return StageSupport.completedStage(false); } private CompletionStage<Boolean> onNext(final T next) { IteratorBackedSubscription.this.subscriber.onNext(next); return StageSupport.completedStage(true); } }); } return fillStage.exceptionally(e -> { if (finish()) { this.iterator.close().whenComplete((ig, closeEx) -> notifySubscriber(false, e, closeEx)); } return null; }); }
Example 12
Source Project: resilience4j File: CompletionStageUtils.java License: Apache License 2.0 | 2 votes |
/** * Returns a CompletionStage that is recovered from any exception. * * @param completionStage the completionStage which should be recovered from any exception * @param exceptionHandler the function applied after callable has failed * @return a CompletionStage that is recovered from any exception. */ public static <T> CompletionStage<T> recover(CompletionStage<T> completionStage, Function<Throwable, T> exceptionHandler){ return completionStage.exceptionally(exceptionHandler); }