Effect TS · Lesson 2 of 8

Typed errors — making failure a value

Effect's big promise, put to the test: everything that can go wrong in a piece of code shows up in its type — and the compiler refuses to let callers ignore it.

Your mission

Lesson 1 listed Effect's promises and turned them into a checklist you'll grade over eight lessons. Row one promised: every Effect program carries its possible failures in its type. Today you test that promise hands-on — and judge whether Effect's packaging beats what you did in Meridian: writing out every possible error yourself, as a list of named cases, and passing it up through every function on the way.

Recall your Meridian pattern

You wrote this shape a dozen times in Meridian — a list of possible failures (a union: one type that is one of several named cases), a Result return (a value holding either a success or an error), and a switch at the call site to see which one arrived:

type OrderError = NotFound | AlreadyPaid;

function pay(order: Order): Result<Receipt, OrderError> { /* … */ }

// caller must switch to know they're safe
switch (result._tag) { /* … */ }

Two pains, both familiar: threading — add one new failure deep inside and you hand-edit every return type on the way up — and escape hatches — one careless throw anywhere and the type stops telling the truth, because a crash can escape that the type never mentions.

The Effect way: the error channel

Every Effect program's type has a second slot: Effect<Success, Error> — what it produces, and everything that can go wrong on the way. Effect calls that second slot the error channel: a dedicated lane that failures travel in. Effect.fail puts a value in that lane; yield* passes failures up it automatically. And the list of possible failures assembles itself — chain three steps whose lanes hold NotFound, AlreadyPaid and CardExpired, and the whole program's lane holds that combined list, written by the compiler, not by you1.

const program = Effect.gen(function* () {
  const order  = yield* findOrder(id);   // can fail NotFound
  const paid   = yield* charge(order);   // can fail CardExpired
  return paid;                            // E = NotFound | CardExpired
});

And when a step fails, the program stops on that line — the rest of the body never runs. It bails out early like a return, except the type system knows it happened.

Declaring failures: TaggedError

You banned classes in Meridian — rightly, because there they pretended to be data models. Here the class isn't a model; it's a mould that stamps out plain objects: each one a simple object with a name label (_tag) plus its details — exactly the union members you used to write by hand2.

import { Data } from 'effect';

// real TypeScript:
class PaymentDeclined extends Data.TaggedError('PaymentDeclined')<{ reason: string }> {}

// the value: { _tag: 'PaymentDeclined', reason: 'over limit' }

The <{ … }> is a TypeScript type argument — a note to the compiler saying which details this error carries, so building one is type-checked. The sandboxes run plain JavaScript, so their code omits it — extends Data.TaggedError('PaymentDeclined'), same runtime behaviour.

Recovering: by tag, not by type

Each stamped error carries its name in _tag, and recovery matches on that name: catchTag handles exactly the failures you name and hands you their details, fully typed. Failures you don't catch stay in the channel — the compiler still makes callers deal with them2. catchAll sweeps up everything, at the cost of no longer knowing which failure actually happened.

Sandbox 1 · fail, short-circuit, catchTag
Verify in the sandbox

Run it: the log line never prints — the gen stopped at the failing yield*. Then: change 9900 to 900 (success path), and finally delete the whole .pipe(…) to see the unhandled red output: Failure :: PaymentDeclined.

The boundary: tryPromise

The ordinary, non-Effect layer of your code — fetch calls, file reads, the JSON parse — reports problems the normal JavaScript way: by throwing. (Effect folks call that layer the imperative shell: the plain-JavaScript skin wrapped around your Effect core.) Effect.tryPromise is the border checkpoint between the two worlds: whatever is thrown on one side comes out the other as a typed failure the compiler knows about1.

const parse = (raw: string) =>
  Effect.tryPromise({
    try:   () => JSON.parseOrThrow(raw),
    catch: (cause) => new JsonBodyError({ cause: String(cause) })
  });
3.22.1 gotcha — verified

Use the object form { try, catch }. The two-argument form tryPromise(fn, onError) compiles but silently ignores your error converter (the catch function that should wrap the thrown error) in version 3.22.1 — failures arrive as UnknownException, Effect's generic "something broke, details unknown" error. With no catch at all, that's the default failure you get; the original error rides along on its .error property.

Sandbox 2 · the imperative-shell boundary

Failures are not defects

Effect splits problems into two kinds: failures — expected outcomes of your business logic (order missing, card declined): typed, and meant to be recovered from — and defects — bugs and impossible states that should crash the program. Effect.die (or Effect.orDie) produces a defect: it never enters the E channel, it lands in the runtime's Cause — Effect's internal record of what actually went wrong — with the tag Die1. In Meridian terms: throw new Error('impossible') — the assertion you'd never want a caller to "handle".

The evaluator's scorecard, so far

Park your verdict — two more rows of the table to test. The typed-errors cheatsheet holds everything from this lesson for reference.

Read one thing

Primary source

Official docs, about 15 minutes: Two error types (failures vs defects — the rule book for keeping the two kinds of problems apart), then Matching (catchTag patterns). After the quiz, not before.

Prove it before you move on

1 · The problem 2 · Typed errors 3 · Schedules & retries 4 · Services & Layers 5 · Schema 6 · HTTP with @effect/platform 7 · Concurrency 8 · The verdict memo
Your teacher

Confused about how yield* passes failures up, when to crash (die) versus fail, or why catchAll loses track of which failure happened? Ask before lesson 3 — retries build directly on today's error channel. Stuck on something the docs explain badly? Say so; I'll re-teach it your way.

← Lesson 1 · Next: Schedules & retries.