Advertisement
Guest User

Untitled

a guest
May 24th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement