Java Code Examples for java.util.concurrent.completionstage#exceptionally()

The following examples show how to use java.util.concurrent.completionstage#exceptionally() . 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 File: CompletableToCompletionStageTest.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
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 File: AsyncExamples.java    From curator with Apache License 2.0 6 votes vote down vote up
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 File: PublisherToCompletionStageTest.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
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 File: SafeFuture.java    From teku with Apache License 2.0 5 votes vote down vote up
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 File: PgSession.java    From pgadba with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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 File: Utils.java    From mug with Apache License 2.0 5 votes vote down vote up
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 File: MaybeTest.java    From mug with Apache License 2.0 5 votes vote down vote up
private static <T> CompletionStage<T> naiveExceptionallyCode(
    CompletionStage<T> stage) {
  return stage.exceptionally(e -> {
    assertThat(e).isInstanceOf(MyException.class);
    return null;
  });
}
 
Example 8
Source File: CompletionStageReturnValueHandler.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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 File: CompletionStageReturnValueHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 File: Boot.java    From docker-nginx-consul with MIT License 5 votes vote down vote up
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 File: FlowAdapter.java    From java-async-util with Apache License 2.0 4 votes vote down vote up
/**
 * 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 File: CompletionStageUtils.java    From resilience4j with Apache License 2.0 2 votes vote down vote up
/**
 * 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);
}