Skip to content

Instantly share code, notes, and snippets.

@the-mgi
Created December 9, 2024 04:38
Show Gist options
  • Select an option

  • Save the-mgi/2cc53261caa0196c41bc5bdede3180b2 to your computer and use it in GitHub Desktop.

Select an option

Save the-mgi/2cc53261caa0196c41bc5bdede3180b2 to your computer and use it in GitHub Desktop.
A wrapper to do functional try catch in case if exception occurs
package com.the_mgi.util;
import java.util.List;
import java.util.function.Supplier;
import static java.util.Objects.nonNull;
import static java.util.Objects.requireNonNull;
public class Catchable<T> {
private final Supplier<T> supplier;
private T result = null;
private Catchable(Supplier<T> supplier) {
this.supplier = supplier;
}
public <E extends Throwable> Catchable<T> execute(List<Class<E>> throwables) {
requireNonNull(throwables);
try {
this.result = this.supplier.get();
return this;
} catch (Throwable exception) {
boolean allThrowablesMatch = true;
for (Class<E> throwable : throwables) {
if (throwable.isInstance(exception)) continue;
allThrowablesMatch = false;
break;
}
if (!allThrowablesMatch) throw new RuntimeException("un-catchable exception: " + exception.getClass());
else this.result = null;
}
return this;
}
public T orElse(T other) {
return nonNull(this.result) ? this.result : other;
}
public T orElseGet(Supplier<T> supplier) {
requireNonNull(supplier);
return nonNull(this.result) ? this.result : supplier.get();
}
public static <T> Catchable<T> of(Supplier<T> supplier) {
requireNonNull(supplier);
return new Catchable<>(supplier);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment