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