fromAsync<T> static method

Future<Result<T>> fromAsync<T>(
  1. Future<T> getter(), {
  2. ExceptionHandler? exceptionHandler,
  3. String? errorGroup,
})

A static method to create a Result instance from an async function that might throw an exception. The ExceptionHandler can be provided to handle exceptions and return an ErrorMessage. The errorGroup can be used to categorize the type of error.

Implementation

static Future<Result<T>> fromAsync<T>(
  Future<T> Function() getter, {
  ExceptionHandler? exceptionHandler,
  String? errorGroup,
}) async {
  assert(
    (exceptionHandler == null && errorGroup == null) ||
        (exceptionHandler != null) ^ (errorGroup != null),
    'Exception handler and error group are mutually exclusive',
  );

  try {
    return Result.success(await getter());
  } on Exception catch (e, s) {
    return Result.failure(
      exceptionHandler?.call(e, s) ??
          ErrorMessage.fromException(e, s, source: errorGroup),
    );
  } catch (e) {
    return Result.failure(
      ErrorMessage(
        message: "Unknown error",
        source: errorGroup,
        details: e,
      ),
    );
  }
}