Skip to content

Commit

Permalink
catchError and catchCause
Browse files Browse the repository at this point in the history
  • Loading branch information
SandroMaglione committed Mar 22, 2024
1 parent a63aae1 commit e82dba6
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
6 changes: 3 additions & 3 deletions examples/poke_api/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ Effect<Env, PokemonError, Pokemon> program(
PokemonIdNotInt.new,
));

if (id < Constants.minimumPokemonId && id > Constants.maximumPokemonId) {
if (id < Constants.minimumPokemonId || id > Constants.maximumPokemonId) {
return $.sync(Effect.fail(const InvalidPokemonIdRange()));
}

Expand Down Expand Up @@ -65,9 +65,9 @@ Effect<Env, PokemonError, Pokemon> program(
});

void main() async {
final exit = await program("72jj1")
final exit = await program("9722")
.map((pokemon) => print(pokemon))
.catchError(
.catchError<void>(
(error) => Effect.function(
() => print("No pokemon: $error"),
),
Expand Down
38 changes: 33 additions & 5 deletions packages/fpdart/lib/src/effect.dart
Original file line number Diff line number Diff line change
Expand Up @@ -103,15 +103,29 @@ final class Effect<E, L, R> extends IEffect<E, L, R> {

/// {@category execution}
Future<R> runFuture(E env) async {
final result = await _unsafeRun(env);
return switch (result) {
final result = _unsafeRun(env);
if (result is! Future) {
print(
"You can use runSync instead of runFuture since the Effect is synchronous",
);
}

return switch (await result) {
Left(value: final cause) => throw cause,
Right(value: final value) => value,
};
}

/// {@category execution}
Future<Exit<L, R>> runFutureExit(E env) async => _unsafeRun(env);
Future<Exit<L, R>> runFutureExit(E env) async {
final result = _unsafeRun(env);
if (result is! Future) {
print(
"You can use runSyncExit instead of runFutureExit since the Effect is synchronous",
);
}
return result;
}

/// {@category constructors}
factory Effect.gen(DoFunctionEffect<E, L, R> f) => Effect<E, L, R>._(
Expand Down Expand Up @@ -366,8 +380,8 @@ final class Effect<E, L, R> extends IEffect<E, L, R> {
);

/// {@category error_handling}
Effect<E, Never, R> catchError(
Effect<E, Never, R> Function(L error) f,
Effect<E, C, R> catchError<C>(
Effect<E, C, R> Function(L error) f,
) =>
Effect._(
(env) => _unsafeRun(env).then(
Expand All @@ -382,6 +396,20 @@ final class Effect<E, L, R> extends IEffect<E, L, R> {
},
),
);

/// {@category error_handling}
Effect<E, C, R> catchCause<C>(
Effect<E, C, R> Function(Cause<L> cause) f,
) =>
Effect._(
(env) => _unsafeRun(env).then(
(exit) => switch (exit) {
Left(value: final cause) => f(cause),
Right(value: final value) => Effect<E, C, R>.succeed(value),
}
._unsafeRun(env),
),
);
}

extension ProvideNever<L, R> on Effect<Never, L, R> {
Expand Down

0 comments on commit e82dba6

Please sign in to comment.