Skip to content

Lesson 5 of 9 · 24m

Result Types: Errors as Values

Replace thrown-control-flow with explicit success and failure values, model expected errors precisely, and still reserve exceptions for exceptional bugs.

JavaScript exceptions are fine for bugs and truly exceptional states. They are miserable for expected business failures: invalid input, missing records, expired sessions, insufficient balance. Those outcomes are part of the domain, yet throw hides them from the type system and forces every caller to guess. A Result type makes failure part of the return value.

Model both tracks

const ok = (value) => ({ ok: true, value });
const err = (error) => ({ ok: false, error });

function parseQuantity(raw) {
  const n = Number(raw);
  if (!Number.isInteger(n)) return err({ code: "not_integer" });
  if (n <= 0) return err({ code: "not_positive" });
  return ok(n);
}

The caller cannot pretend failure does not exist:

const parsed = parseQuantity(form.quantity);
if (!parsed.ok) showFieldError(parsed.error.code);
else submit(parsed.value);

This is the monadic part without jargon: a wrapped value plus predictable ways to transform it without unpacking at every step.

map and chain keep the success path straight

const map = (result, fn) => result.ok ? ok(fn(result.value)) : result;
const chain = (result, fn) => result.ok ? fn(result.value) : result;

Use map when the next step cannot fail. Use chain when it returns another Result and may fail. The names matter less than the distinction.

Match errors deliberately

function describeQuantityError(error) {
  switch (error.code) {
    case "not_integer": return "Quantity must be a whole number";
    case "not_positive": return "Quantity must be above zero";
    default: return "Invalid quantity";
  }
}

Failure cases become enumerable, testable, and visible in one place. Compare that with catching Error and matching human-readable message strings.

Exceptions still have a job

Throw when the programmer violated an invariant: impossible state, corrupted data, missing configuration. Return err when the user or outside world did something expected. If every failure is thrown, callers cannot reason. If programmer bugs become data, they get routed into UI copy and disappear.

Field notes

  • Discriminated unions work best with a literal tag like ok; do not infer failure from payload shape.
  • Use stable error codes plus details. Strings alone are for humans, not control flow.
  • TypeScript can enforce exhaustive handling with a never check in the default branch.
  • Libraries like neverthrow and fp-ts exist, but a small local Result implementation often covers the need.

Was this lesson helpful?

Sign in to rate