runCatchingAsync<T> function
Runs the passed in async function catching any thrown error objects and returning it as a result monad.
If the function completes without throwing an exception its corresponding value is returned. If an exception is thrown then an error monad will be returned instead.
final sizeResult = await runCatching(()async{
final file = File(filename);
final stat = await file.stats();
return stat.fileSize();
});
sizeResult.match(
(size) => print('File size: $size'),
(error) => print('Error accessing $filename: $error')
);
Implementation
FutureResult<T, dynamic> runCatchingAsync<T>(
FutureResult<T, dynamic> Function() function) async {
try {
return await function();
} catch (e) {
return Result.error(e);
}
}