runCatching<T> function
Runs the passed in 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 = runCatching((){
final file = File(filename);
final stat = file.statsSync();
return stat.fileSize();
});
sizeResult.match(
(size) => print('File size: $size'),
(error) => print('Error accessing $filename: $error')
);
Implementation
Result<T, dynamic> runCatching<T>(Result<T, dynamic> Function() function) {
try {
return function();
} catch (e) {
return Result.error(e);
}
}