Skip to content

Instantly share code, notes, and snippets.

@douglas444
Created November 14, 2025 21:26
Show Gist options
  • Select an option

  • Save douglas444/a6ced20b10b3f4ae59a48a6f1b22b3ac to your computer and use it in GitHub Desktop.

Select an option

Save douglas444/a6ced20b10b3f4ae59a48a6f1b22b3ac to your computer and use it in GitHub Desktop.
import java.util.function.Function;
import java.util.function.Supplier;
public class Result<T> {
private final boolean success;
private final String errorMessage;
private final T data;
private Result(boolean success, String errorMessage, T data) {
this.success = success;
this.errorMessage = errorMessage;
this.data = data;
}
public static <T> Result<T> success(T data) {
return new Result<>(true, null, data);
}
public static Result<Void> success() {
return new Result<>(true, null, null);
}
public static <T> Result<T> failure(String errorMessage) {
Assert.required(errorMessage);
return new Result<>(false, errorMessage, null);
}
public T orElseThrow(Function<String, RuntimeException> function) {
Assert.required(function);
if (this.success) {
return this.data;
} else {
throw function.apply(this.errorMessage);
}
}
public static <T, E extends RuntimeException> Result<T> trySupplier(
Supplier<T> supplier,
Class<E> recoverableType
) {
try {
return Result.success(supplier.get());
} catch (RuntimeException e) {
if (recoverableType.isInstance(e)) {
return Result.failure(e.getMessage());
}
throw e;
}
}
public boolean isSuccess() {
return success;
}
public boolean isFailure() {
return !success;
}
public String getErrorMessage() {
return errorMessage;
}
public T getData() {
return data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment