from<R, T> static method

Result<R> from<R, T>(
  1. T func(), {
  2. R onSuccess(
    1. T result
    )?,
  3. BaseError onError(
    1. Object error,
    2. StackTrace stackTrace
    )?,
})

Constructs a Result from a function. If the function completes successfully, the Result is a success with the value of the function. If the function fails, the Result is an error with the error of the function.

Implementation

static Result<R> from<R, T>(
  T Function() func, {
  R Function(T result)? onSuccess,
  BaseError Function(Object error, StackTrace stackTrace)? onError,
}) {
  try {
    final result = func();
    if (onSuccess != null) {
      return successResult(onSuccess(result));
    }
    return successResult(result.cast<R>());
  } catch (error, stackTrace) {
    if (onError != null) {
      return errorResult(onError(error, stackTrace));
    }
    return errorResult(BaseError.fromError(error, stackTrace));
  }
}