Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Result<T> {
- private final T result;
- private final Throwable error;
- public Result(T result, Throwable error) {
- this.result = result;
- this.error = error;
- }
- public Throwable error() {
- return error;
- }
- public boolean isError() {
- return error != null;
- }
- public T get() {
- if (result == null) {
- throw new RuntimeException("Try to get failed result", error);
- }
- return result;
- }
- @SuppressWarnings("unchecked")
- public <E extends Throwable> Result<T> onError(Class<E> cls, Consumer<E> catchBlock) {
- if (cls.isInstance(error)) {
- catchBlock.accept((E) error);
- }
- return this;
- }
- public static <T> Result<T> ofThrowable(ThrowableSupplier<T> supplier) {
- try {
- return new Result<>(supplier.supply(), null);
- } catch (Throwable error) {
- return new Result<T>(null, error);
- }
- }
- }
- @FunctionalInterface
- interface ThrowableSupplier<T> {
- T supply() throws Throwable;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement