Result<T extends Object?, E extends Object>.guardSync constructor

Result<T extends Object?, E extends Object>.guardSync(
  1. T block()
)

Executes a synchronous function and wraps the result.

Attempts to execute block and wraps any matching thrown value in Err with its stack trace. Returns Ok if successful. For catching only Exception types, use guardExceptionSync instead.

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

Example:

final result = Result<int, FormatException>.guardSync(
  () => int.parse('30'),
);

Implementation

factory Result.guardSync(T Function() block) {
  try {
    final value = block();
    return .ok(value);
  } on E catch (e, st) {
    return .err(e, st);
  }
}