Error handling
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.
Catching: the error is unknown
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:
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:
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:
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:
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:
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:
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:
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:
function fail(message: string): never {
throw new Error(message);
}
const port = Number(process.env.PORT) || fail("PORT must be set"); // numberRemember: caught errors are
unknown— narrow them; subclassErrorand passcausefor useful errors; and when failure is a normal outcome, return it in the type.
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.
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"];const PRICES: Record<string, number> = { "LMP-01": 24.99, "NB-A5": 3.5 };
type OrderLine = { sku: string; quantity: number };
// 1. Result
type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };
const ok = <T,>(value: T): Result<T, never> => ({ ok: true, value });
const err = <E,>(error: E): Result<never, E> => ({ ok: false, error });
// 2. OrderError
type OrderError =
| { kind: "empty" }
| { kind: "badQuantity"; line: number }
| { kind: "unknownSku"; sku: string };
// 3. parseOrder
function parseOrder(text: string): Result<OrderLine[], OrderError> {
const parts = text.split(",").map((p) => p.trim()).filter((p) => p !== "");
if (parts.length === 0) return err({ kind: "empty" });
const lines: OrderLine[] = [];
for (const [index, part] of parts.entries()) {
const [sku = "", qty = ""] = part.split(/\s+x/);
const quantity = Number(qty);
if (!Number.isInteger(quantity) || quantity < 1) return err({ kind: "badQuantity", line: index + 1 });
if (!(sku in PRICES)) return err({ kind: "unknownSku", sku });
lines.push({ sku, quantity });
}
return ok(lines);
}
// 4. describeError
function describeError(error: OrderError): string {
switch (error.kind) {
case "empty": return "The order is empty";
case "badQuantity": return `Line ${error.line} needs a quantity of at least 1`;
case "unknownSku": return `We don't sell "${error.sku}"`;
default: {
const unreachable: never = error;
return unreachable;
}
}
}
const inputs = ["LMP-01 x2, NB-A5 x3", "", "LMP-01 x0", "PEN-9 x1"];
for (const input of inputs) {
const result = parseOrder(input);
if (result.ok) {
const total = result.value.reduce((sum, line) => sum + (PRICES[line.sku] ?? 0) * line.quantity, 0);
console.log(`OK: ${result.value.length} lines, total ${total.toFixed(2)}`);
} else {
console.log(`Error: ${describeError(result.error)}`);
}
}
// 5. OrderNotFoundError and loadOrder
class OrderNotFoundError extends Error {
override name = "OrderNotFoundError";
readonly orderId: string;
constructor(orderId: string, options?: ErrorOptions) {
super(`Order ${orderId} was not found`, options);
this.orderId = orderId;
}
}
function loadOrder(id: string): never {
const dbError = new Error("404 from orders table");
throw new OrderNotFoundError(id, { cause: dbError });
}
try {
loadOrder("o-404");
} catch (error) {
if (error instanceof OrderNotFoundError) {
const cause = error.cause instanceof Error ? error.cause.message : "unknown";
console.log(`${error.name}: ${error.message} (id ${error.orderId}, cause: ${cause})`);
} else {
throw error;
}
}Summary
- Caught errors are
unknown: narrow withinstanceof 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
Resultunion: 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.