Catch One Error, Not the World (Learning Effect, Part 6)

By Esteban Trillo2 min readupdated Learning EffectEffectTypeScript

Patch the one leak you can handle. The database leak still shows.
Patch the one leak you can handle. The database leak still shows.

try/catch is often too wide.

You want to handle one known failure. But the catch block can grab everything.

That is how bugs get hidden.

let user: User;
try {
user = await fetchUser(1);
} catch {
user = { id: 1, name: "Guest" };
}

This was meant for a missing user.

It also catches a database outage.

It catches a typo inside fetchUser.

All of them become a guest.

The catch block has no idea which one it got.

It does not ask.

That is fine for one missing user.

It is a quiet outage when the database is down for everyone.

Effect gives you a smaller move: catchTag.

Handle one error

const program = fetchUser(1).pipe(
Effect.catchTag("UserNotFound", () =>
Effect.succeed({ id: 1, name: "Guest" }),
),
);

This handles UserNotFound.

It does not mean every possible error is gone.

What does catchTag('UserNotFound', ...) handle?

The error slot gets smaller

Before:

Effect.Effect<User, UserNotFound | DatabaseDown, UserRepo>;

After handling UserNotFound:

Effect.Effect<User, DatabaseDown, UserRepo>;

That is the win.

The type changes because the program changed.

After handling UserNotFound, which error can still remain?

The mistake: reaching for Effect.catch

Effect also has Effect.catch. Effect 3 called it catchAll.

const program = fetchUser(1).pipe(
Effect.catch(() => Effect.succeed({ id: 1, name: "Guest" })),
);

It handles every error in the slot.

The type becomes:

Effect.Effect<User, never, UserRepo>;

An empty error slot looks like a win.

Here it is a warning. DatabaseDown also turned into a guest.

That is the wide try/catch again, with nicer types.

Effect.catch is still useful.

At the very edge, turning every leftover error into a 500 response is fine.

Deep in the program, it hides the errors you most need to see.

Pick the narrow tool first.

Widen it only where you mean it.

How to spot it: the error slot went to never, and you only meant to handle one thing.

catchTag checks the name too. catchTag("UserNotFund", ...) does not compile. No error in the slot has that tag.

Do not catch what you cannot fix

This is the part I care about.

If I can turn UserNotFound into a guest user, fine.

If the database is down, I probably should not pretend everything is okay.

Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.