SHARE
TWEET

Untitled

a guest May 24th, 2019 76 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Result<T> {
  2.     private final T result;
  3.     private final Throwable error;
  4.  
  5.     public Result(T result, Throwable error) {
  6.         this.result = result;
  7.         this.error = error;
  8.     }
  9.  
  10.     public Throwable error() {
  11.         return error;
  12.     }
  13.  
  14.     public boolean isError() {
  15.         return error != null;
  16.     }
  17.  
  18.     public T get() {
  19.         if (result == null) {
  20.             throw new RuntimeException("Try to get failed result", error);
  21.         }
  22.         return result;
  23.     }
  24.  
  25.     @SuppressWarnings("unchecked")
  26.     public <E extends Throwable> Result<T> onError(Class<E> cls, Consumer<E> catchBlock) {
  27.         if (cls.isInstance(error)) {
  28.             catchBlock.accept((E) error);
  29.         }
  30.         return this;
  31.     }
  32.  
  33.     public static <T> Result<T> ofThrowable(ThrowableSupplier<T> supplier) {
  34.         try {
  35.             return new Result<>(supplier.supply(), null);
  36.         } catch (Throwable error) {
  37.             return new Result<T>(null, error);
  38.         }
  39.     }
  40. }
  41.  
  42. @FunctionalInterface
  43. interface ThrowableSupplier<T> {
  44.     T supply() throws Throwable;
  45. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top