java-commons/src/main/java/io/gitlab/jfronny/commons/throwable/ThrowingFunction.java

75 lines
2.6 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;
@FunctionalInterface
public interface ThrowingFunction<T, R, TEx extends Throwable> {
R apply(T var1) throws TEx;
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
default ThrowingSupplier<R, TEx> compose(@NotNull ThrowingSupplier<? extends T, ? extends TEx> before) {
Objects.requireNonNull(before);
return () -> this.apply(before.get());
}
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
default <V> ThrowingFunction<V, R, TEx> compose(@NotNull ThrowingFunction<? super V, ? extends T, ? extends TEx> before) {
Objects.requireNonNull(before);
return (v) -> this.apply(before.apply(v));
}
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
default <V> ThrowingFunction<T, V, TEx> andThen(@NotNull ThrowingFunction<? super R, ? extends V, ? extends TEx> after) {
Objects.requireNonNull(after);
return (t) -> after.apply(this.apply(t));
}
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
default ThrowingConsumer<T, TEx> andThen(@NotNull ThrowingConsumer<? super R, ? extends TEx> after) {
Objects.requireNonNull(after);
return (t) -> after.accept(this.apply(t));
}
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
default Function<T, R> addHandler(@NotNull Function<Throwable, ? extends R> handler) {
Objects.requireNonNull(handler);
return (t) -> {
try {
return this.apply(t);
} catch (Throwable e) {
return handler.apply(e);
}
};
}
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
default Function<T, R> addHandler(@NotNull Class<TEx> exception, Function<TEx, ? extends R> handler) {
Objects.requireNonNull(handler);
return (t) -> {
try {
return this.apply(t);
} 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 Function<T, R> orThrow() {
return (t) -> {
try {
return this.apply(t);
} catch (Throwable e) {
throw Try.runtimeException(e);
}
};
}
}