ensure function

Result<()> ensure(
  1. bool fn(),
  2. Object err, [
  3. StackTrace? stackTrace
])

Convenience function for creating a Result to return with the err if the condition does not hold.

final check = ensure(() => x > 1, "x should be greater than 1");
if(check.isErr()) return check;

stackTrace will be ignored if Error.hasStackTrace is false.

Implementation

Result<()> ensure(bool Function() fn, Object err, [StackTrace? stackTrace]) {
  assert(err is! Error, _isAlreadyErrorAssertionMessage);
  if (fn()) {
    return const Ok(());
  }
  if (Error.hasStackTrace) {
    if (stackTrace == null) {
      return Err(Error._withStackTrace(err, StackTrace.current));
    }
    return Err(Error._withStackTrace(err, stackTrace));
  }
  return Err(Error(err));
}