runCatching<T> function

Result<T, dynamic> runCatching<T>(
  1. Result<T, dynamic> function()
)

Allows library users to wrap potential exception throwing code in a way that transforms thrown exception objects into a failure monad. 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);
  }
}