throwIfNeeded method

T throwIfNeeded()

Forcefully unwraps the successful value or throws a managed ResultException.

Use this when integrating with legacy codebases, third-party libraries, or system methods that absolutely require native try-catch block architectures.

Throws a ResultException encapsulating the underlying Failure contract if it is a failure state.

try {
  final user = userResult.throwIfNeeded();
} on ResultException catch (e) {
  print(e.failure.message);
}

Implementation

T throwIfNeeded() {
  return switch (this) {
    SuccessResult<T>(success: Success(:final value)) => value,
    FailureResult<T>(failure: final fail) => throw ResultException(fail),
  };
}