guardAsync<T extends Object?, E extends Object> static method
Executes an asynchronous function and wraps the result.
Attempts to execute asyncBlock and wraps any exception in Err with
the captured stack trace. Returns Ok if the async operation succeeds,
Err if an exception matching type E is thrown. For catching Exception
types specifically, 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);
}
}