1. Concept library
  2. JavaScript & TypeScript
  3. Module 11: Errors and validation

Concept

Error handling patterns

Decide where errors are caught and what callers get: thrown exceptions for bugs and unexpected failures, returned results for failures the caller is expected to handle. Mixing the two makes both unreliable.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain when to throw an exception and when to return a result
  2. Write a function that returns a result type for failures the caller must handle
  3. Spot the catch that logs and carries on with a half-finished state

In practice

A few lines that show Error handling patterns doing its job.

TypeScript
type Result<T> = { ok: true; value: T } | { ok: false; error: string };

function parsePort(text: string): Result<number> {
  const n = Number(text);
  if (!Number.isInteger(n) || n < 1 || n > 65535) {
    return { ok: false, error: "port must be 1-65535, got " + text };
  }
  return { ok: true, value: n };
}

const port = parsePort(process.env.PORT ?? "");
if (!port.ok) throw new Error(port.error);

The common mistake

Watch for

Catching an error only to log it and carry on. The caller then works with a half-finished state and the real failure shows up later somewhere unrelated.

What to know first

Your roadmap puts these before Error handling patterns, unless you already know them.

How it stays learned

Once a session shows you understand Error handling patterns, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Error handling patterns.

Next in the moduleThe unknown type →