Error handling

Topic 2 of 3 in Async code and runtime safety7 min readIntermediateFree course

Overview

TypeScript checks the happy path thoroughly, but JavaScript’s error handling is untyped: any function can throw anything, and a throws declaration doesn’t exist. This lesson shows how to handle thrown errors safely, how to make your own errors more useful, and how to move expected failures into the type system where the compiler can check them.

Two ways to handle errors. Throw and catch: try { await saveOrder(order); } catch (err) { — err is unknown — if (err instanceof Error) { console.error(err.message); } else { console.error(String(err)); } } — anything can be thrown, so caught values are unknown and must be narrowed. Return a Result: type Result<T, E = string> = { ok: true; value: T } | { ok: false; error: E }; const r = parsePrice(text); if (r.ok) use(r.value); else show(r.error); — failure is part of the type, so callers cannot forget to handle it. Use exceptions for unexpected failures; use Result-style return values for failures callers should always handle.

Catching: the error is unknown

TypeScript
try {
  JSON.parse(text);
} catch (error) {
  console.log(error.message);
  // error TS18046: 'error' is of type 'unknown'.
}

With strict mode (the useUnknownInCatchVariables check), the caught value is unknown, because JavaScript lets code throw strings, numbers, null — anything. Narrow it:

TypeScript
catch (error) {
  if (error instanceof SyntaxError) {
    console.log("Bad JSON:", error.message);
  } else if (error instanceof Error) {
    console.log("Unexpected:", error.message);
  } else {
    console.log("Something odd was thrown:", String(error));
  }
}

A small helper keeps this tidy:

TypeScript
function errorMessage(error: unknown): string {
  return error instanceof Error ? error.message : String(error);
}

Don’t swallow errors

Catch an error only if you can do something useful — retry, fall back, add context, show a message. Otherwise let it propagate, or rethrow after logging:

TypeScript
catch (error) {
  if (error instanceof NotFoundError) return null;   // expected: handle it
  throw error;                                       // anything else: not our job
}

Custom error classes

Subclass Error to make error kinds distinguishable with instanceof, and to carry extra, typed data:

TypeScript
class HttpError extends Error {
  override name = "HttpError";
  readonly status: number;

  constructor(status: number, message: string, options?: ErrorOptions) {
    super(message, options);
    this.status = status;
  }
}

try {
  throw new HttpError(404, "User not found");
} catch (error) {
  if (error instanceof HttpError && error.status === 404) {
    // error.status: number
  }
}

Setting name makes stack traces and logs show HttpError rather than Error.

Wrapping with cause

When you catch a low-level error and throw a more meaningful one, pass the original as cause — it keeps the full story for debugging:

TypeScript
try {
  await db.query(sql);
} catch (error) {
  throw new Error(`Could not load order ${id}`, { cause: error });
}

cause is standard JavaScript (ErrorOptions), shown by Node in stack traces. Its type is unknown, so narrow it when reading it.

Returning errors: Result types

Exceptions are invisible in function signatures. Looking at function parsePrice(text: string): number, nothing tells you it might throw, and nothing forces callers to handle it. For failures that are a normal outcome — invalid user input, “not found”, a payment declined — you can make the failure part of the return type:

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

function parsePrice(text: string): Result<number, string> {
  const value = Number(text);
  if (!Number.isFinite(value) || value < 0) {
    return { ok: false, error: `"${text}" is not a valid price` };
  }
  return { ok: true, value };
}

const result = parsePrice(input);
result.value;
// error TS2339: Property 'value' does not exist on type 'Result<number, string>'.
//   Property 'value' does not exist on type '{ ok: false; error: string; }'.

if (result.ok) {
  total += result.value;          // ✓ narrowed: value exists
} else {
  showError(result.error);
}

It’s a discriminated union (Discriminated unions), so the caller can’t use the value without checking. And the error type can itself be a precise union, so callers can handle each case — with an exhaustive switch if they like:

TypeScript
type SignupError =
  | { kind: "emailTaken" }
  | { kind: "weakPassword"; reasons: string[] }
  | { kind: "rateLimited"; retryAfter: number };

Throw or return?

Throw an exception when… Return a Result when…
it’s a bug or a broken invariant the failure is an expected outcome
the caller can’t reasonably recover the caller must decide what to do
failing fast is the right behaviour you want the compiler to enforce handling
e.g. missing config, programming errors e.g. validation, not found, declined

Many codebases use both: Result values inside the business logic, and a top-level try/catch (in a request handler or main) for the unexpected.

Never-returning helpers

A function that always throws has return type never, which lets TypeScript narrow after calling it:

TypeScript
function fail(message: string): never {
  throw new Error(message);
}

const port = Number(process.env.PORT) || fail("PORT must be set");   // number

Remember: caught errors are unknown — narrow them; subclass Error and pass cause for useful errors; and when failure is a normal outcome, return it in the type.

Exercise

Parse an order safely

(1) Define type Result<T, E> = { ok: true; value: T } | { ok: false; error: E } with helpers ok(value) and err(error). (2) Define type OrderError = { kind: "empty" } | { kind: "badQuantity"; line: number } | { kind: "unknownSku"; sku: string }. (3) Write parseOrder(text: string): Result<OrderLine[], OrderError> for input like "LMP-01 x2, NB-A5 x3" — each line is SKU xN with N a positive integer and SKU in the PRICES table. (4) Write describeError(error: OrderError): string with an exhaustive switch. (5) Define class OrderNotFoundError extends Error with a readonly orderId and cause support, throw it from loadOrder("o-404"), and catch it with instanceof, printing the message, the id and the cause. Print results for four inputs in the starter.

TypeScript
const PRICES: Record<string, number> = { "LMP-01": 24.99, "NB-A5": 3.5 };
type OrderLine = { sku: string; quantity: number };

// 1–4

// 5. OrderNotFoundError and loadOrder

const inputs = ["LMP-01 x2, NB-A5 x3", "", "LMP-01 x0", "PEN-9 x1"];

Summary

  • Caught errors are unknown: narrow with instanceof Error (or your own classes) before using them.
  • Custom error classes extend Error, can carry typed extra data, and should pass { cause } along when wrapping.
  • Rethrow errors you don’t know how to handle instead of swallowing them.
  • For expected failures, return a Result union: the failure is part of the type, so callers must handle it.
  • Throw for bugs and unexpected conditions; return errors for outcomes the caller should plan for.