64 lines
2.1 KiB
Java
64 lines
2.1 KiB
Java
package io.gitlab.jfronny.commons.throwable;
|
|
|
|
import org.jetbrains.annotations.ApiStatus;
|
|
import org.jetbrains.annotations.Contract;
|
|
import org.jetbrains.annotations.NotNull;
|
|
|
|
import java.util.Objects;
|
|
import java.util.function.Function;
|
|
import java.util.function.Supplier;
|
|
|
|
@FunctionalInterface
|
|
public interface ThrowingSupplier<T, TEx extends Throwable> {
|
|
T get() throws TEx;
|
|
|
|
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
|
|
default <V> ThrowingSupplier<V, TEx> andThen(@NotNull ThrowingFunction<? super T, ? extends V, ? extends TEx> after) {
|
|
Objects.requireNonNull(after);
|
|
return () -> after.apply(this.get());
|
|
}
|
|
|
|
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
|
|
default ThrowingRunnable<TEx> andThen(@NotNull ThrowingConsumer<? super T, ? extends TEx> after) {
|
|
Objects.requireNonNull(after);
|
|
return () -> after.accept(this.get());
|
|
}
|
|
|
|
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
|
|
default Supplier<T> addHandler(@NotNull Function<Throwable, ? extends T> handler) {
|
|
Objects.requireNonNull(handler);
|
|
return () -> {
|
|
try {
|
|
return this.get();
|
|
} catch (Throwable e) {
|
|
return handler.apply(e);
|
|
}
|
|
};
|
|
}
|
|
|
|
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
|
|
default Supplier<T> addHandler(@NotNull Class<TEx> exception, @NotNull Function<TEx, ? extends T> handler) {
|
|
Objects.requireNonNull(handler);
|
|
return () -> {
|
|
try {
|
|
return this.get();
|
|
} catch (Throwable e) {
|
|
if (exception.isAssignableFrom(e.getClass()))
|
|
return handler.apply((TEx) e);
|
|
else throw Try.runtimeException(e);
|
|
}
|
|
};
|
|
}
|
|
|
|
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
|
|
default Supplier<T> orThrow() {
|
|
return () -> {
|
|
try {
|
|
return this.get();
|
|
} catch (Throwable e) {
|
|
throw Try.runtimeException(e);
|
|
}
|
|
};
|
|
}
|
|
}
|