ensure method
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,
};