tryOrElse<T> function

T tryOrElse<T>(
  1. T action(),
  2. T onError(
    1. Object error,
    2. StackTrace stackTrace
    )
)

Executes action, recovering from a thrown error with onError.

Unlike tryOrNull and tryOrDefault, which discard the error, onError receives both the error and its stack trace, so the recovery can log or branch on what actually went wrong.

Example:

final config = tryOrElse(
  () => parseConfig(raw),
  (error, stackTrace) {
    log.warning('Falling back to defaults', error, stackTrace);
    return Config.defaults();
  },
);

Implementation

T tryOrElse<T>(
  T Function() action,
  T Function(Object error, StackTrace stackTrace) onError,
) {
  try {
    return action();
  } catch (error, stackTrace) {
    return onError(error, stackTrace);
  }
}