All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fm.pattern.valex.Result Maven / Gradle / Ivy

package fm.pattern.valex;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import fm.pattern.commons.util.JSON;

public class Result {

    private final T instance;
    private final List errors = new ArrayList<>();

    private Result(T instance) {
        this.instance = instance;
    }

    private Result(T instance, Reportable... errors) {
        this.instance = instance;
        this.errors.addAll(Arrays.asList(errors));
    }

    public static  Result accept(T instance) {
        return new Result<>(instance);
    }

    public static  Result reject(String keyOrMessage, Object... arguments) {
        return new Result<>(null, Reportable.report(keyOrMessage, arguments));
    }

    public static  Result reject(Reportable... errors) {
        return new Result<>(null, errors);
    }

    public T getInstance() {
        return instance;
    }

    public T orThrow() {
        if (rejected()) {
            throw ReportableExceptionRaiser.raise(errors);
        }
        return instance;
    }

    public T orThrow(Class exception) {
        if (rejected()) {
            throw ReportableExceptionRaiser.raise(exception, errors);
        }
        return instance;
    }

    public boolean accepted() {
        return errors.isEmpty();
    }

    public boolean rejected() {
        return !errors.isEmpty();
    }

    public List getErrors() {
        return new ArrayList<>(this.errors);
    }

    @Override
    public String toString() {
        return JSON.stringify(this);
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy