Lesson 03 of 6 in Effect, one function at a time

Recover one error with Effect.catchTag

Recover from one tagged error and leave the others alone.

Once an effect can fail with several tagged errors, Effect.catchTag lets you handle exactly one of them and let the rest continue.

import { Effect } from "effect";

type ModelError =
	| { readonly _tag: "RateLimited"; readonly retryAfter: number }
	| { readonly _tag: "Network"; readonly detail: string };

const callModel = (ok: boolean): Effect.Effect<string, ModelError> =>
	ok
		? Effect.succeed("answer")
		: Effect.fail({ _tag: "RateLimited", retryAfter: 2 });

export const answer = (ok: boolean) =>
	callModel(ok).pipe(
		Effect.catchTag("RateLimited", (e) =>
			Effect.succeed(`wait ${e.retryAfter}s`),
		),
	);

Three things to notice:

Use it instead of a catch-all when only one failure has a sensible fallback. A catch-all hides the cases you did not think about.