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 exception in Err with the current stack trace. Returns Ok if successful, Err if an exception matching type E is thrown. For catching Exception types specifically, 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 guardSync(T Function() block) {
  try {
    final value = block();
    return .ok(value);
  } on E catch (e, st) {
    return .err(e, st);
  }
}