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

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

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

Try.getCause介绍

[英]Gets the cause if this is a Failure or throws if this is a Success.
[中]如果这是失败的,获取原因;如果这是成功的,则抛出。

代码示例

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

default void orElseRun(Consumer<? super Throwable> action) {
  Objects.requireNonNull(action, "action is null");
  if (isFailure()) {
    action.accept(getCause());
  }
}

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

private Response<T> handleFailure(Try<Response<T>> response) throws IOException {
  try {
    throw response.getCause();
  } catch (RequestNotPermitted | IllegalStateException e) {
    return tooManyRequestsError();
  } catch (IOException ioe) {
    throw ioe;
  } catch (Throwable t) {
    throw new RuntimeException("Exception executing call", t);
  }
}

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

default <X extends Throwable> T getOrElseThrow(Function<? super Throwable, X> exceptionProvider) throws X {
  Objects.requireNonNull(exceptionProvider, "exceptionProvider is null");
  if (isFailure()) {
    throw exceptionProvider.apply(getCause());
  } else {
    return get();
  }
}

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

default T getOrElseGet(Function<? super Throwable, ? extends T> other) {
  Objects.requireNonNull(other, "other is null");
  if (isFailure()) {
    return other.apply(getCause());
  } else {
    return get();
  }
}

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

/**
 * Folds either the {@code Failure} or the {@code Success} side of the Try value.
 *
 * @param ifFail  maps the left value if this is a {@code Failure}
 * @param f maps the value if this is a {@code Success}
 * @param <X>         type of the folded value
 * @return A value of type X
 */
default <X> X fold(Function<? super Throwable, ? extends X> ifFail, Function<? super T, ? extends X> f) {
  if (isFailure()) {
    return ifFail.apply(getCause());
  } else {
    return f.apply(get());
  }
}

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

/**
 * Returns {@code Success(throwable)} if this is a {@code Failure(throwable)}, otherwise
 * a {@code Failure(new NoSuchElementException("Success.failed()"))} if this is a Success.
 *
 * @return a new Try
 */
default Try<Throwable> failed() {
  if (isFailure()) {
    return new Success<>(getCause());
  } else {
    return new Failure<>(new NoSuchElementException("Success.failed()"));
  }
}

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

/**
 * Creates a {@code Validation} of an {@code Try}.
 *
 * @param t      A {@code Try}
 * @param <T>    type of the valid value
 * @return A {@code Valid(t.get())} if t is a Success, otherwise {@code Invalid(t.getCause())}.
 * @throws NullPointerException if {@code t} is null
 */
static <T> Validation<Throwable, T> fromTry(Try<? extends T> t) {
  Objects.requireNonNull(t, "t is null");
  return t.isSuccess() ? valid(t.get()) : invalid(t.getCause());
}

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

/**
 * Converts this {@code Try} to a {@link Validation}, converting the Throwable (if present)
 * to another object using passed {@link Function}.
 *
 * <pre>{@code
 * Validation<String, Integer> = Try.of(() -> 1/0).toValidation(Throwable::getMessage));
 * }</pre>
 *
 * @param <U> result type of the throwable mapper
 * @param throwableMapper  A transformation from throwable to desired invalid type of new {@code Validation}
 * @return A new {@code Validation}
 * @throws NullPointerException if the given {@code throwableMapper} is null.
 */
default <U> Validation<U, T> toValidation(Function<? super Throwable, ? extends U> throwableMapper) {
  Objects.requireNonNull(throwableMapper, "throwableMapper is null");
  if (isFailure()) {
    return Validation.invalid(throwableMapper.apply(getCause()));
  } else {
    return Validation.valid(get());
  }
}

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

/**
 * Converts this {@code Try} to an {@link Either}.
 *
 * @return A new {@code Either}
 */
default Either<Throwable, T> toEither() {
  if (isFailure()) {
    return Either.left(getCause());
  } else {
    return Either.right(get());
  }
}

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

/**
 * Reduces many {@code Try}s into a single {@code Try} by transforming an
 * {@code Iterable<Try<? extends T>>} into a {@code Try<Seq<T>>}. If any of
 * the {@code Try}s are {@link Try.Failure}, then this returns a {@link Try.Failure}.
 *
 * @param values An {@link Iterable} of {@code Try}s
 * @param <T>    type of the Trys
 * @return A {@code Try} of a {@link Seq} of results
 * @throws NullPointerException if {@code values} is null
 */
static <T> Try<Seq<T>> sequence(Iterable<? extends Try<? extends T>> values) {
  Objects.requireNonNull(values, "values is null");
  Vector<T> vector = Vector.empty();
  for (Try<? extends T> value : values) {
    if (value.isFailure()) {
      return Try.failure(value.getCause());
    }
    vector = vector.append(value.get());
  }
  return Try.success(vector);
}

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

@Test
public void decorateConsumer() throws Exception {
  Consumer<Integer> consumer = mock(Consumer.class);
  Consumer<Integer> decorated = RateLimiter.decorateConsumer(limit, consumer);
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(false);
  Try<Integer> decoratedConsumerResult = Try.success(1).andThen(decorated);
  then(decoratedConsumerResult.isFailure()).isTrue();
  then(decoratedConsumerResult.getCause()).isInstanceOf(RequestNotPermitted.class);
  verify(consumer, never()).accept(any());
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(true);
  Try secondConsumerResult = Try.success(1).andThen(decorated);
  then(secondConsumerResult.isSuccess()).isTrue();
  verify(consumer, times(1)).accept(1);
}

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

@Test
public void decorateFunction() throws Exception {
  Function<Integer, String> function = mock(Function.class);
  Function<Integer, String> decorated = RateLimiter.decorateFunction(limit, function);
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(false);
  Try<String> decoratedFunctionResult = Try.success(1).map(decorated);
  then(decoratedFunctionResult.isFailure()).isTrue();
  then(decoratedFunctionResult.getCause()).isInstanceOf(RequestNotPermitted.class);
  verify(function, never()).apply(any());
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(true);
  Try secondFunctionResult = Try.success(1).map(decorated);
  then(secondFunctionResult.isSuccess()).isTrue();
  verify(function, times(1)).apply(1);
}

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

/**
 * A projection that inverses the result of this Future.
 * <p>
 * If this Future succeeds, the failed projection returns a failure containing a {@code NoSuchElementException}.
 * <p>
 * If this Future fails, the failed projection returns a success containing the exception.
 *
 * @return A new Future which contains an exception at a point of time.
 */
default Future<Throwable> failed() {
  return run(executor(), complete ->
    onComplete(result -> {
      if (result.isFailure()) {
        complete.with(Try.success(result.getCause()));
      } else {
        complete.with(Try.failure(new NoSuchElementException("Future.failed completed without a throwable")));
      }
    })
  );
}

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

@Test
public void decorateRunnable() throws Exception {
  Runnable runnable = mock(Runnable.class);
  Runnable decorated = RateLimiter.decorateRunnable(limit, runnable);
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(false);
  Try decoratedRunnableResult = Try.success(decorated).andThen(Runnable::run);
  then(decoratedRunnableResult.isFailure()).isTrue();
  then(decoratedRunnableResult.getCause()).isInstanceOf(RequestNotPermitted.class);
  verify(runnable, never()).run();
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(true);
  Try secondRunnableResult = Try.success(decorated).andThen(Runnable::run);
  then(secondRunnableResult.isSuccess()).isTrue();
  verify(runnable, times(1)).run();
}

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

@Test
public void decorateSupplier() throws Exception {
  Supplier supplier = mock(Supplier.class);
  Supplier decorated = RateLimiter.decorateSupplier(limit, supplier);
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(false);
  Try decoratedSupplierResult = Try.success(decorated).map(Supplier::get);
  then(decoratedSupplierResult.isFailure()).isTrue();
  then(decoratedSupplierResult.getCause()).isInstanceOf(RequestNotPermitted.class);
  verify(supplier, never()).get();
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(true);
  Try secondSupplierResult = Try.success(decorated).map(Supplier::get);
  then(secondSupplierResult.isSuccess()).isTrue();
  verify(supplier, times(1)).get();
}

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

@Test
public void decorateCheckedRunnable() throws Throwable {
  CheckedRunnable runnable = mock(CheckedRunnable.class);
  CheckedRunnable decorated = RateLimiter.decorateCheckedRunnable(limit, runnable);
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(false);
  Try decoratedRunnableResult = Try.run(decorated);
  then(decoratedRunnableResult.isFailure()).isTrue();
  then(decoratedRunnableResult.getCause()).isInstanceOf(RequestNotPermitted.class);
  verify(runnable, never()).run();
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(true);
  Try secondRunnableResult = Try.run(decorated);
  then(secondRunnableResult.isSuccess()).isTrue();
  verify(runnable, times(1)).run();
}

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

/**
 * Maps the cause to a new exception if this is a {@code Failure} or returns this instance if this is a {@code Success}.
 * <p>
 * If none of the given cases matches the cause, the same {@code Failure} is returned.
 *
 * @param cases A not necessarily exhaustive sequence of cases that will be matched against a cause.
 * @return A new {@code Try} if this is a {@code Failure}, otherwise this.
 */
@GwtIncompatible
@SuppressWarnings({ "unchecked", "varargs" })
default Try<T> mapFailure(Match.Case<? extends Throwable, ? extends Throwable>... cases) {
  if (isSuccess()) {
    return this;
  } else {
    final Option<Throwable> x = Match(getCause()).option(cases);
    return x.isEmpty() ? this : failure(x.get());
  }
}

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

@Test
public void decorateCheckedSupplier() throws Throwable {
  CheckedFunction0 supplier = mock(CheckedFunction0.class);
  CheckedFunction0 decorated = RateLimiter.decorateCheckedSupplier(limit, supplier);
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(false);
  Try decoratedSupplierResult = Try.of(decorated);
  then(decoratedSupplierResult.isFailure()).isTrue();
  then(decoratedSupplierResult.getCause()).isInstanceOf(RequestNotPermitted.class);
  verify(supplier, never()).apply();
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(true);
  Try secondSupplierResult = Try.of(decorated);
  then(secondSupplierResult.isSuccess()).isTrue();
  verify(supplier, times(1)).apply();
}

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

@Test
public void decorateCheckedFunction() throws Throwable {
  CheckedFunction1<Integer, String> function = mock(CheckedFunction1.class);
  CheckedFunction1<Integer, String> decorated = RateLimiter.decorateCheckedFunction(limit, function);
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(false);
  Try<String> decoratedFunctionResult = Try.success(1).mapTry(decorated);
  then(decoratedFunctionResult.isFailure()).isTrue();
  then(decoratedFunctionResult.getCause()).isInstanceOf(RequestNotPermitted.class);
  verify(function, never()).apply(any());
  when(limit.getPermission(config.getTimeoutDuration()))
    .thenReturn(true);
  Try secondFunctionResult = Try.success(1).mapTry(decorated);
  then(secondFunctionResult.isSuccess()).isTrue();
  verify(function, times(1)).apply(1);
}

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

@Test
  public void executeFutureSupplier() throws Throwable {
    Future<Integer> future = EXECUTOR_SERVICE.submit(() -> {
          Thread.sleep(SLEEP_DURATION.toMillis());
          return 1;
        }
    );

    Supplier<Future<Integer>> supplier = () -> future;

    Try decoratedResult = Try.of(() -> TimeLimiter.of(shortConfig).executeFutureSupplier(supplier));
    then(decoratedResult.isFailure()).isTrue();
    then(decoratedResult.getCause()).isInstanceOf(TimeoutException.class);
    then(future.isCancelled()).isTrue();

    Future<Integer> secondFuture = EXECUTOR_SERVICE.submit(() -> {
          Thread.sleep(SLEEP_DURATION.toMillis());
          return 1;
        }
    );

    Supplier<Future<Integer>> secondSupplier = () -> secondFuture;

    Try secondResult = Try.of(() -> TimeLimiter.of(longConfig).executeFutureSupplier(secondSupplier));
    then(secondResult.isSuccess()).isTrue();
  }
}

相关文章