io.vavr.control.Try.onFailure()方法的使用及代码示例

x33g5p2x  于2022-01-30 转载在 其他  
字(8.1k)|赞(0)|评价(0)|浏览(418)

本文整理了Java中io.vavr.control.Try.onFailure()方法的一些代码示例,展示了Try.onFailure()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Try.onFailure()方法的具体详情如下:
包路径:io.vavr.control.Try
类名称:Try
方法名:onFailure

Try.onFailure介绍

[英]Consumes the cause if this is a Try.Failure and the cause is instance of X.

// (does not print anything)

[中]如果这是一次尝试,则消耗原因。失败,原因是X实例。

// (does not print anything)

代码示例

代码示例来源:origin: vavr-io/vavr

/**
 * Performs the action once the Future is complete and the result is a {@link Try.Failure}. Please note that the
 * future is also a failure when it was cancelled.
 *
 * @param action An action to be performed when this future failed.
 * @return this Future
 * @throws NullPointerException if {@code action} is null.
 */
default Future<T> onFailure(Consumer<? super Throwable> action) {
  Objects.requireNonNull(action, "action is null");
  return onComplete(result -> result.onFailure(action));
}

代码示例来源:origin: vavr-io/vavr

/**
 * Converts this to a {@link CompletableFuture}
 *
 * @return A new {@link CompletableFuture} containing the value
 */
@GwtIncompatible
default CompletableFuture<T> toCompletableFuture() {
  final CompletableFuture<T> completableFuture = new CompletableFuture<>();
  Try.of(this::get)
      .onSuccess(completableFuture::complete)
      .onFailure(completableFuture::completeExceptionally);
  return completableFuture;
}

代码示例来源:origin: resilience4j/resilience4j

private void exec(Runnable runnable, int times) {
  for (int i = 0; i < times; i++) {
    Try.runRunnable(runnable)
      .onFailure(e -> System.out.println(e.getMessage()));
  }
}

代码示例来源:origin: vavr-io/vavr

/**
 * Transforms the value of this {@code Future}, whether it is a success or a failure.
 *
 * @param f   A transformation
 * @param <U> Generic type of transformation {@code Try} result
 * @return A {@code Future} of type {@code U}
 * @throws NullPointerException if {@code f} is null
 */
default <U> Future<U> transformValue(Function<? super Try<T>, ? extends Try<? extends U>> f) {
  Objects.requireNonNull(f, "f is null");
  return run(executor(), complete ->
    onComplete(t -> Try.run(() -> complete.with(f.apply(t)))
        .onFailure(x -> complete.with(Try.failure(x)))
    )
  );
}

代码示例来源:origin: vavr-io/vavr

default <U> Future<U> flatMapTry(CheckedFunction1<? super T, ? extends Future<? extends U>> mapper) {
  Objects.requireNonNull(mapper, "mapper is null");
  return run(executor(), complete ->
    onComplete(result -> result.mapTry(mapper)
        .onSuccess(future -> future.onComplete(complete::with))
        .onFailure(x -> complete.with(Try.failure(x)))
    )
  );
}

代码示例来源:origin: vavr-io/vavr

.onFailure(ignored -> {
  if (wasLast) {
    completed.set(complete.with(Try.success(Option.none())));

代码示例来源:origin: vavr-io/vavr

/**
 * Handles a failure of this Future by returning the result of another Future.
 * <p>
 * Example:
 * <pre><code>
 * // = "oh!"
 * Future.of(() -&gt; { throw new Error("oh!"); }).recoverWith(x -&gt; Future.of(x::getMessage));
 * </code></pre>
 *
 * @param f A function which takes the exception of a failure and returns a new future.
 * @return A new Future.
 * @throws NullPointerException if {@code f} is null
 */
default Future<T> recoverWith(Function<? super Throwable, ? extends Future<? extends T>> f) {
  Objects.requireNonNull(f, "f is null");
  return run(executor(), complete ->
    onComplete(t -> {
      if (t.isFailure()) {
        Try.run(() -> f.apply(t.getCause()).onComplete(complete::with))
            .onFailure(x -> complete.with(Try.failure(x)));
      } else {
        complete.with(t);
      }
    })
  );
}

代码示例来源:origin: io.vavr/vavr

/**
 * Performs the action once the Future is complete and the result is a {@link Try.Failure}. Please note that the
 * future is also a failure when it was cancelled.
 *
 * @param action An action to be performed when this future failed.
 * @return this Future
 * @throws NullPointerException if {@code action} is null.
 */
default Future<T> onFailure(Consumer<? super Throwable> action) {
  Objects.requireNonNull(action, "action is null");
  return onComplete(result -> result.onFailure(action));
}

代码示例来源:origin: TinkoffCreditSystems/QVisual

public static void post(String url, String snapshot) {
  Try.of(() -> {
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new StringEntity(snapshot, "UTF-8"));
    HttpResponse response = client.execute(httpPost);
    return new BasicResponseHandler().handleResponse(response);
  }).onFailure(t -> logger.error("[POST snapshot]", t));
}

代码示例来源:origin: com.mercateo.eventstore/client-common

public Either<EventStoreFailure, String> toJsonString(Object data) {
  return Try //
    .of(() -> objectMapper.writeValueAsString(data))
    .onFailure(e -> log.warn("could not deserialize {}", data != null ? data.getClass().getSimpleName() : null,
        e))
    .toEither()
    .mapLeft(this::mapInternalError);
}

代码示例来源:origin: TinkoffCreditSystems/QVisual

public static Try<String> writeAsString(Object json) {
  return Try.of(() -> getMapper().writeValueAsString(json)).onFailure(t -> logger.error("[write json]", t));
}

代码示例来源:origin: TinkoffCreditSystems/QVisual

public static <T> Try<T> parseJson(String json, TypeReference<T> type) {
  return (Try<T>) Try.of(() -> getMapper().readValue(json, type)).onFailure(t -> logger.error("[parse json]", t));
}

代码示例来源:origin: io.vavr/vavr

/**
 * Converts this to a {@link CompletableFuture}
 *
 * @return A new {@link CompletableFuture} containing the value
 */
@GwtIncompatible
default CompletableFuture<T> toCompletableFuture() {
  final CompletableFuture<T> completableFuture = new CompletableFuture<>();
  Try.of(this::get)
      .onSuccess(completableFuture::complete)
      .onFailure(completableFuture::completeExceptionally);
  return completableFuture;
}

代码示例来源:origin: Tristan971/Lyrebird

public void openUserDetails(final String screenName) {
  findUser(screenName)
      .onSuccess(this::openUserDetails)
      .onFailure(err -> ExceptionHandler.displayExceptionPane(
          "Unknown user!",
          "Can't map this user's screen name (@...) to an actual Twitter user!",
          err
      ));
}

代码示例来源:origin: Tristan971/Lyrebird

@Override
public void refresh() {
  if (!sessionManager.isLoggedInProperty().getValue()) {
    LOG.debug("Logged out, not refreshing direct messages.");
    return;
  }
  CompletableFuture.runAsync(() -> {
    LOG.debug("Requesting last direct messages.");
    sessionManager.getCurrentTwitter()
           .mapTry(twitter -> twitter.getDirectMessages(20))
           .onSuccess(this::addDirectMessages)
           .onFailure(err -> LOG.error("Could not load direct messages successfully!", err));
  });
}

代码示例来源:origin: Tristan971/Lyrebird

public void openUserDetails(final long targetUserId) {
  findUser(targetUserId)
      .onSuccess(this::openUserDetails)
      .onFailure(err -> ExceptionHandler.displayExceptionPane(
          "Unknown user!",
          "Can't map this user's userId to an actual Twitter user!",
          err
      ));
}

代码示例来源:origin: Tristan971/Lyrebird

/**
 * Fetches, shows and moves the main application stage to the front.
 */
private void showMainStage() {
  CompletableFuture.runAsync(
      () -> stageManager.getSingle(Screen.ROOT_VIEW)
               .toTry(IllegalStateException::new)
               .onSuccess(stage -> {
                 stage.show();
                 stage.setIconified(false);
               }).onFailure(err -> LOG.error("Could not show main stage!", err)),
      Platform::runLater
  );
}

代码示例来源:origin: Tristan971/Lyrebird

/**
 * Loads the current user's account view on the top of the bar.
 */
private void loadCurrentAccountPanel() {
  easyFxml.loadNode(CURRENT_ACCOUNT)
      .getNode()
      .onSuccess(container::setTop)
      .onFailure(err -> displayExceptionPane(
          "Could not load current user!",
          "There was an error mapping the current session to a twitter account.",
          err
      ));
}

代码示例来源:origin: io.vavr/vavr

/**
 * Transforms the value of this {@code Future}, whether it is a success or a failure.
 *
 * @param f   A transformation
 * @param <U> Generic type of transformation {@code Try} result
 * @return A {@code Future} of type {@code U}
 * @throws NullPointerException if {@code f} is null
 */
default <U> Future<U> transformValue(Function<? super Try<T>, ? extends Try<? extends U>> f) {
  Objects.requireNonNull(f, "f is null");
  return run(executor(), complete ->
    onComplete(t -> Try.run(() -> complete.with(f.apply(t)))
        .onFailure(x -> complete.with(Try.failure(x)))
    )
  );
}

代码示例来源:origin: io.vavr/vavr

default <U> Future<U> flatMapTry(CheckedFunction1<? super T, ? extends Future<? extends U>> mapper) {
  Objects.requireNonNull(mapper, "mapper is null");
  return run(executor(), complete ->
    onComplete(result -> result.mapTry(mapper)
        .onSuccess(future -> future.onComplete(complete::with))
        .onFailure(x -> complete.with(Try.failure(x)))
    )
  );
}

相关文章