All Downloads are FREE. Search and download functionalities are using the official Maven repository.

xdean.jex.extra.tryto.Failure Maven / Gradle / Ivy

The newest version!
package xdean.jex.extra.tryto;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * @author [email protected]
 *
 */
public class Failure extends Try {

  private final Exception exception;

  Failure(Exception e) {
    exception = e;
  }

  @Override
  public boolean isFailure() {
    return true;
  }

  @Override
  public boolean isSuccess() {
    return false;
  }

  @Override
  public T get() {
    throw new RuntimeException(exception.getMessage(), exception);
  }

  @Override
  public Try foreach(Consumer f) {
    // do nothing
    return this;
  }

  @SuppressWarnings("unchecked")
  @Override
  public  Try flatMap(Function> f) {
    return (Try) this;
  }

  @SuppressWarnings("unchecked")
  @Override
  public  Try map(Function f) {
    return (Try) this;
  }

  @Override
  public Try filter(Predicate p) {
    return this;
  }

  @Override
  public Try recoverWith(Function> f) {
    try {
      return f.apply(exception);
    } catch (Exception e) {
      return new Failure<>(e);
    }
  }

  @Override
  public Try recover(Function f) {
    try {
      return Try.to(() -> f.apply(exception));
    } catch (RuntimeException e) {
      return new Failure<>(e);
    }
  }

  @Override
  public Try failed() {
    return new Success<>(exception);
  }

  @Override
  public  Try transform(Function> s, Function> f) {
    try {
      return f.apply(exception);
    } catch (RuntimeException e) {
      return new Failure<>(e);
    }
  }

  @Override
  public Try onException(Consumer f) {
    f.accept(exception);
    return this;
  }

}