Outcome
The Outcome<T>
class represents the result of a resilience pipeline execution, containing either a successful result or exception information.
Overview
The Outcome class provides a type-safe way to handle both successful and failed operations. It encapsulates the result value, exception details, and provides utility methods for outcome analysis.
class Outcome<T> {
const Outcome.success(T result);
const Outcome.failure(Exception exception);
bool get hasResult;
bool get hasException;
T get result;
Exception get exception;
T getResultOrThrow();
T getResultOrDefault(T defaultValue);
T? getResultOrNull();
Outcome<U> map<U>(U Function(T) mapper);
Outcome<U> flatMap<U>(Outcome<U> Function(T) mapper);
Outcome<T> recover(T Function(Exception) recovery);
Outcome<T> onSuccess(void Function(T) action);
Outcome<T> onFailure(void Function(Exception) action);
}
Constructors
Outcome.success(T result)
Creates a successful outcome with the specified result.
Parameters:
result
- The successful result value
final outcome = Outcome.success('Hello World');
print(outcome.hasResult); // true
print(outcome.result); // Hello World
Outcome.failure(Exception exception)
Creates a failed outcome with the specified exception.
Parameters:
exception
- The exception that occurred
final outcome = Outcome.failure(TimeoutException('Request timed out'));
print(outcome.hasException); // true
print(outcome.exception); // TimeoutException
Properties
hasResult
Gets a value indicating whether the outcome contains a successful result.
Type: bool
if (outcome.hasResult) {
print('Operation succeeded: ${outcome.result}');
}
hasException
Gets a value indicating whether the outcome contains an exception.
Type: bool
if (outcome.hasException) {
print('Operation failed: ${outcome.exception}');
}
result
Gets the successful result value. Throws if the outcome is a failure.
Type: T
Throws: StateError
if the outcome is a failure
try {
final value = outcome.result;
print('Success: $value');
} on StateError {
print('Cannot access result on failed outcome');
}
exception
Gets the exception. Throws if the outcome is successful.
Type: Exception
Throws: StateError
if the outcome is successful
try {
final error = outcome.exception;
print('Error: $error');
} on StateError {
print('Cannot access exception on successful outcome');
}
Methods
getResultOrThrow()
Gets the result value or throws the contained exception.
Returns: T
- The result value
Throws: The contained exception if the outcome is a failure
try {
final value = outcome.getResultOrThrow();
print('Success: $value');
} catch (e) {
print('Failed: $e');
}
getResultOrDefault(T defaultValue)
Gets the result value or returns the specified default value if the outcome is a failure.
Parameters:
defaultValue
- The value to return if the outcome is a failure
Returns: T
- The result value or default value
final value = outcome.getResultOrDefault('default');
print('Value: $value'); // Returns result or 'default'