90 lines
2.9 KiB
Java
90 lines
2.9 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.Consumer;
|
|
|
|
@FunctionalInterface
|
|
public interface ThrowingConsumer<T, TEx extends Throwable> {
|
|
void accept(T var1) throws TEx;
|
|
|
|
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
|
|
default <V> ThrowingConsumer<V, TEx> compose(@NotNull ThrowingFunction<? super V, ? extends T, ? extends TEx> before) {
|
|
Objects.requireNonNull(before);
|
|
return (t) -> this.accept(before.apply(t));
|
|
}
|
|
|
|
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
|
|
default ThrowingRunnable<TEx> compose(@NotNull ThrowingSupplier<? extends T, ? extends TEx> before) {
|
|
Objects.requireNonNull(before);
|
|
return () -> this.accept(before.get());
|
|
}
|
|
|
|
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
|
|
default ThrowingConsumer<T, TEx> andThen(@NotNull ThrowingConsumer<? super T, ? extends TEx> after) {
|
|
Objects.requireNonNull(after);
|
|
return (t) -> {
|
|
this.accept(t);
|
|
after.accept(t);
|
|
};
|
|
}
|
|
|
|
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
|
|
default ThrowingConsumer<T, TEx> andThen(@NotNull ThrowingRunnable<? extends TEx> after) {
|
|
Objects.requireNonNull(after);
|
|
return (t) -> {
|
|
this.accept(t);
|
|
after.run();
|
|
};
|
|
}
|
|
|
|
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
|
|
default <V> ThrowingBiConsumer<T, V, TEx> compound(@NotNull ThrowingConsumer<? super V, ? extends TEx> other) {
|
|
Objects.requireNonNull(other);
|
|
return (l, r) -> {
|
|
this.accept(l);
|
|
other.accept(r);
|
|
};
|
|
}
|
|
|
|
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
|
|
default Consumer<T> addHandler(@NotNull Consumer<Throwable> handler) {
|
|
Objects.requireNonNull(handler);
|
|
return (t) -> {
|
|
try {
|
|
this.accept(t);
|
|
} catch (Throwable e) {
|
|
handler.accept(e);
|
|
}
|
|
};
|
|
}
|
|
|
|
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
|
|
default Consumer<T> addHandler(@NotNull Class<TEx> exception, @NotNull Consumer<TEx> handler) {
|
|
Objects.requireNonNull(handler);
|
|
return (t) -> {
|
|
try {
|
|
this.accept(t);
|
|
} catch (Throwable e) {
|
|
if (exception.isAssignableFrom(e.getClass()))
|
|
handler.accept((TEx) e);
|
|
else throw Try.runtimeException(e);
|
|
}
|
|
};
|
|
}
|
|
|
|
@Contract(pure = true) @NotNull @ApiStatus.NonExtendable
|
|
default Consumer<T> orThrow() {
|
|
return (t) -> {
|
|
try {
|
|
this.accept(t);
|
|
} catch (Throwable e) {
|
|
throw Try.runtimeException(e);
|
|
}
|
|
};
|
|
}
|
|
}
|