package {{context.group}}.{{context.project}}.ext; import lombok.Data; import lombok.AllArgsConstructor; import java.util.Optional; import java.util.function.Function; @Data @AllArgsConstructor public class MayFail { Exception ex; T result; public static MayFail from(T result) { return new MayFail<>(null, result); } public static MayFail from(Exception error) { return new MayFail<>(error, null); } public interface MayFailProvider { R func() throws Exception; } public static MayFail from(MayFailProvider mayFailProvider) { try { return MayFail.from(mayFailProvider.func()); } catch (Exception ex) { return MayFail.from(ex); } } public boolean isSuccess() { return ex == null; } public T get() { return result; } public T getOrDefault(T defaultResult) { return ex == null ? result : defaultResult; } public MayFail map(Function mapFunc) { if (ex == null) { return MayFail.from(mapFunc.apply(result)); } else { return MayFail.from(ex); } } public Optional mapOption(Function mapFunc) { return Optional.ofNullable(mapFunc.apply(result)); } }