Errors You Can Actually See in Effect (Learning Effect, Part 5)

By Esteban Trillo2 min readupdated Learning EffectEffectTypeScript

Open the error slot and read every way it can fail, before you run it.
Open the error slot and read every way it can fail, before you run it.

JavaScript lets any function throw almost anything.

A string. An Error. A random object. Something from a library you did not know was inside the call stack.

TypeScript does not show that in the function type.

Effect does.

The plain version

try {
const user = await getUser(input);
} catch (error) {
// what is error?
}

With strict on, error is unknown.

TypeScript cannot know what was thrown, so it does not guess.

You check with instanceof and hope your list is complete.

Nothing tells you when a new error appears deeper in the stack.

That is the problem Effect is trying to fix.

Give errors names

class InvalidUserId {
readonly _tag = "InvalidUserId";
constructor(readonly input: string) {}
}
class UserNotFound {
readonly _tag = "UserNotFound";
constructor(readonly id: number) {}
}

The _tag looks odd at first. It gives the error a stable name.

That makes it easy to handle one error later.

Why add a _tag to Effect errors?

The type becomes honest

const program = parseUserId(input).pipe(Effect.flatMap(fetchUser));

The type can say:

Effect.Effect<User, InvalidUserId | UserNotFound, never>;

That is useful before you run anything.

You can see what the caller must care about.

Which errors can this program fail with?

The mistake: errors as strings

Strings are the fastest way to fail.

const program = Effect.fail("User not found");

The type is Effect.Effect<never, string, never>.

That compiles. It also tells the caller almost nothing.

Two different failures both look like string.

You cannot catch one by name.

A typo in the message changes nothing in the type.

Matching on message text is how the old try/catch code worked.

It breaks the day someone edits the wording.

new Error("...") has the same problem. Every failure becomes Error.

How to spot it: read the error slot. If it says string or Error, the names are missing.

Give each failure its own class with a _tag.

The _tag is what catchTag reads in the next part.

This changes the conversation

Without Effect, I often ask:

Does this throw?

With Effect, I ask:

What does the error slot say?

That is a better question.

It moves failure from memory into the type.

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.