guardAsync<T extends Object?, E extends Object> static method

Future<Result<T, E>> guardAsync<T extends Object?, E extends Object>(
  1. Future<T> asyncBlock()
)

Executes an asynchronous function and wraps the result.

Attempts to execute asyncBlock and wraps any matching thrown value in Err with its stack trace. Returns Ok if the async operation succeeds. For catching only Exception types, use guardExceptionAsync instead.

Note: Only catches E or subtypes of E. Other exceptions will propagate uncaught.

This is the async counterpart to guardSync. Stack traces are preserved for better debugging.

Example:

final result = await Result<String, HttpException>.guardAsync(
  () => fetchData(),
);

Implementation

static Future<Result<T, E>> guardAsync<T extends Object?, E extends Object>(
  Future<T> Function() asyncBlock,
) async {
  try {
    final value = await asyncBlock();
    return .ok(value);
  } on E catch (e, st) {
    return .err(e, st);
  }
}