ensure method

Result<T> ensure(
  1. bool predicate(
    1. T data
    ),
  2. Failure onUnmet(
    1. T data
    )
)

If this is a Success and predicate returns false for its data, converts it into an Error using onUnmet. Otherwise propagates the result unchanged. Handy for post-success domain validation, e.g. an HTTP 200 envelope whose body still indicates a logical failure.

final r = await api.fetchOrder(id);
final valid = r.ensure(
  (o) => o.items.isNotEmpty,
  (o) => const Failure.badResponse(message: 'Empty order'),
);

Implementation

Result<T> ensure(
  bool Function(T data) predicate,
  Failure Function(T data) onUnmet,
) =>
    switch (this) {
      Success<T>(:final data) =>
        predicate(data) ? this : Error<T>(onUnmet(data)),
      Error<T>() => this,
    };