error_or 0.0.5 copy "error_or: ^0.0.5" to clipboard
error_or: ^0.0.5 copied to clipboard

outdated

Return a result ErrorOr with either a value T or an error Object.

ErrorOr #

Return a result ErrorOr with either a value T or an error Object.

Features #

Always return a valid value ErrorOr from an async function. Let the called / inner function handle the error and return an ErrorOr. This way the caller / outer function can await the result without a try catch.

A subclass of ErrorOr contains either the expected value T or an error Object (usually an Exception returned from a try catch).

Internally, we create a private subclass of ErrorOr, either a _ValueWrapper or an _ErrorWrapper, with the expected non-null value.

ErrorOr can be used for non-async functions too - for both Flutter and Dart.

Getting started #

Make a function return a Future<ErrorOr>, which you'll await in the calling function.

Create a ErrorOr instance by calling one of its factory methods value or error.

Check if hasError, before calling error, or check if hasValue before calling value. If either is called without the proper check, an ErrorOrTypeCastError is thrown.

Usage #

Example

Future<ErrorOr<LocationPermission>> checkPermission() async {
  try {
    return ErrorOr.value(await Geolocator.checkPermission());
  } catch (e) {
    return ErrorOr.error(e);
  }
}
ErrorOr<LocationPermission> errorOrPermission = await checkPermission();
if (errorOrPermission.hasError) {
  return errorOrPermission;
}
LocationPermission permission = errorOrPermission.value;

Additional information #

I would like to keep this package minimal, but please get in touch on github if you have suggestions to improvements.

The name was inspired by the ErrorOr type of SerenityOS.

The Success / Failure pattern was inspired by result_type.

5
likes
0
pub points
42%
popularity

Publisher

verified publisherapptakk.com

Return a result ErrorOr with either a value T or an error Object.

Repository (GitHub)
View/report issues

License

unknown (LICENSE)

More

Packages that depend on error_or