mapErrorToResult<NewFailure extends Object> method
- @optionalTypeArgs
- Result<
Success, NewFailure> transform(- Failure error
When this Result is a success, simply return the
value
as-is. When this Result is a failure,
transform
the error
into a new Result.
After the transformation, isSuccess
may be different
between the new and old Results—the transform IS
allowed to change the nature of the outcome.
A Result.success will always transform to a Result.success.
A Result.failure may transform to either a Result.success or a Result.failure.
Useful to recover from some error
s by returning a
success value when a workaround exists. The value
must match the success type, but the error type can
change.
Here, mapErrorToResult is used to ignore errors
which can be resolved by a cache lookup. Both
unrecoverable DioError
s and internal errors
accessing the cache are expressed in the more generic
FetchError
of the final output.
final Result<Person, DioError> raw = await dioGetApiPerson(id);
final Result<Person, FetchError> output = raw.mapErrorToResult((error) => _getPersonCache(id));
Result<Person, FetchError> _getPersonCache(int id) {
// ...
}
Here, an initial failure is transformed into a success whenever the required value is available in the local cache.
Implementation
@optionalTypeArgs
Result<Success, NewFailure> mapErrorToResult<NewFailure extends Object>(
Result<Success, NewFailure> Function(Failure error) transform,
) =>
when(
success: (value) => Result.success(value),
failure: (error) => transform(error),
);