The Analogy: The Returns Desk at a Depot's Goods-In Bay
A distribution depot has a goods-in bay where returned items come back from customers, and a clerk on the returns desk who has to deal with whatever arrives. The clerk would love every return to be a neatly filled-in returns form with an order number, a reason code, and the item boxed as it went out. In practice the box might hold a proper form, or a reason scrawled on the back of a receipt, or a single word on a scrap of paper, or nothing at all but the item, because a customer can put anything in a return. The clerk cannot assume the tidy form; they have to open the box and look before they can act.
That box of unknown contents is exactly a caught error. JavaScript lets code throw any value at all: a proper Error object with a message and a stack, but equally a bare string, a number, null, or a random object. Nothing forces a thrown value to be an Error. So when the language hands the caught value to the catch clause, the honest type for it is unknown, and the clerk must inspect it before treating it as anything specific. Reaching for the message on it before checking is assuming the tidy form that may not be there.
The depot copes by normalising at the desk. However the return arrives, the clerk fills out one standard internal docket from it, so that everything downstream, the stock system, the refund process, the audit trail, sees a uniform record rather than the raw mess. In code that is a toError helper that turns any caught value into a real Error, called once at the point of catching, so every log and every report works with a consistent shape. Returns that the depot recognises, a warranty claim or a wrong-size exchange, carry a category code the clerk routes on; those are custom error classes with a discriminant field, so a switch can send each known kind down its own path.
The failure mode is a clerk who acts on the assumed form without opening the box, and one who quietly bins a return they do not understand. Reading the order number off a return that turned out to be an empty envelope gets nonsense, exactly as reading error.message off a thrown string gets undefined. Worse is the clerk who, faced with a return they cannot categorise, drops it in the bin rather than escalating it: an empty catch that swallows the error turns a real failure into a silent mystery, and a genuine bug vanishes with no trace. The rule at the desk is that anything you cannot handle gets passed up the chain, which in code is rethrowing what you do not recognise rather than swallowing it.
Syntax or Core Structure
A caught value is typed unknown, so you must narrow it before use. The everyday pattern checks instanceof Error and falls back for anything else.
// src/catching.ts
function describe(thrown: unknown): string {
try {
throw thrown;
} catch (error) {
if (error instanceof Error) {
return "error: " + error.message;
}
if (typeof error === "string") {
return "string: " + error;
}
return "other: " + String(error);
}
}
console.log(describe(new Error("boom")));
console.log(describe("oops"));
console.log(describe(42));
Output:
error: boom
string: oops
other: 42
The catch variable is unknown, so error.message cannot be read until the type is proven. The first call throws a real Error, so instanceof Error passes and the message "boom" is read. The second throws a string, caught by the typeof branch as "oops". The third throws a number, which falls through to the final branch and is stringified to "42". Each value had to be inspected before it could be used, exactly as the clerk opens each box.
Technical Depth: Normalise Once, Then Route
Writing the instanceof dance in every catch clause gets tedious, and it scatters the same three lines all over the codebase. The depot's answer is to normalise at the desk: however the return arrives, fill out one standard docket from it. In code that is a single helper that turns any caught value into a real Error, called once at the point of catching.
One helper turns anything into an Error
// src/normalise.ts
function toError(value: unknown): Error {
if (value instanceof Error) {
return value;
}
if (typeof value === "string") {
return new Error(value);
}
return new Error("non-error thrown: " + String(value));
}
function attempt(thrown: unknown): string {
const error = toError(thrown);
return error.message;
}
console.log(attempt(new Error("disk full")));
console.log(attempt("timeout"));
console.log(attempt({ code: 500 }));
Output:
disk full
timeout
non-error thrown: [object Object]
The first call already holds an Error, so toError hands it straight back and the message "disk full" survives untouched. The second is a bare string, wrapped in a fresh Error so its own text becomes the message. The third is a plain object, which has no message of its own, so it is stringified: String({ code: 500 }) produces "[object Object]", which is exactly the docket you want on an item that arrived without a proper label. Every downstream logger now sees an Error with a .message, never the raw mess.
Custom errors as a discriminated union
// src/apperror.ts
class ValidationError extends Error {
readonly kind = "validation";
constructor(readonly field: string, message: string) {
super(message);
this.name = "ValidationError";
}
}
class NetworkError extends Error {
readonly kind = "network";
constructor(readonly status: number) {
super("request failed with " + status);
this.name = "NetworkError";
}
}
type AppError = ValidationError | NetworkError;
function isAppError(value: unknown): value is AppError {
return value instanceof ValidationError || value instanceof NetworkError;
}
function route(caught: unknown): string {
if (!isAppError(caught)) {
return "rethrow: unrecognised";
}
switch (caught.kind) {
case "validation":
return "field " + caught.field + ": " + caught.message;
case "network":
return caught.status >= 500 ? "retry later" : "fix request";
}
}
console.log(route(new ValidationError("email", "must not be blank")));
console.log(route(new NetworkError(503)));
console.log(route(new NetworkError(400)));
console.log(route("weird"));
Output:
field email: must not be blank
retry later
fix request
rethrow: unrecognised
The readonly kind field on each class turns the two error types into a discriminated union, so switch (caught.kind) narrows and caught.field is reachable only inside the "validation" branch where it exists. isAppError is the door: anything that is not one of our two recognised kinds returns "rethrow: unrecognised", which in real code would be throw caught. That single line is the difference between a bug that surfaces and one that vanishes. Note the two housekeeping rules for subclassing Error: always set this.name, and if you compile down to ES5 add Object.setPrototypeOf in the constructor or instanceof silently stops working.
Throw or return: two honest choices
A thrown error is invisible in a function's signature; getUser(id: number): Promise<User> says nothing about what can go wrong. The alternative is to return the failure as a value using a Result type, which puts the failure in the signature where the compiler can enforce handling.
// src/result.ts
type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
function half(n: number): Result<number> {
if (n % 2 !== 0) {
return { ok: false, error: new Error("odd: " + n) };
}
return { ok: true, value: n / 2 };
}
for (const n of [8, 5, 12]) {
const outcome = half(n);
if (outcome.ok) {
console.log(n + " -> " + outcome.value);
} else {
console.log(n + " -> " + outcome.error.message);
}
}
Output:
8 -> 4
5 -> odd: 5
12 -> 6
The compiler will not let you read outcome.value until you have checked outcome.ok, so the failure cannot be forgotten. The two styles are not rivals so much as tools for different jobs, and the table below is the rule most teams settle on.
| Aspect | throw | Result |
|---|---|---|
| Visible in the signature | no | yes |
| Compiler forces handling | no | yes |
| Call-site noise | none | a check per call |
| Stack trace | automatic | only if you build one |
| Best suited to | programmer bugs | expected, recoverable failures |
A Result shines for the failures you expect and must handle, such as validation and HTTP, while a plain throw stays right for the bugs that should abort loudly. There is one more subtlety on the async path: inside a try block, prefer return await op() over return op(), because without the await a finally block runs its cleanup before the operation actually finishes.
Real World Example: A Batch Importer That Sorts Its Own Returns
A nightly job imports a batch of rows into a ledger. Each row is validated and then saved, and any of them can fail in two recognised ways: it can be malformed (a validation fault), or the ledger can refuse it (a save fault). The importer catches at the row level, narrows the caught value to decide which kind of fault it was, and produces a uniform Outcome for every row so the batch can print one clean report and carry on rather than dying on the first bad row.
// src/import.ts
type Row = { ref: string; email: string; amount: number };
type Outcome =
| { status: "saved"; ref: string; amount: number }
| { status: "validation"; ref: string; message: string }
| { status: "save"; ref: string; message: string };
class ValidationFault extends Error {
readonly kind = "validation";
constructor(readonly field: string, message: string) {
super(message);
this.name = "ValidationFault";
}
}
class SaveFault extends Error {
readonly kind = "save";
constructor(message: string) {
super(message);
this.name = "SaveFault";
}
}
function toError(value: unknown): Error {
if (value instanceof Error) {
return value;
}
return new Error("non-error thrown: " + String(value));
}
function validate(row: Row): void {
if (row.email.length === 0) {
throw new ValidationFault("email", "email is blank");
}
if (row.amount <= 0) {
throw new ValidationFault("amount", "amount must be positive");
}
}
function save(row: Row): number {
if (row.ref.startsWith("x")) {
throw new SaveFault("ledger rejected " + row.ref);
}
return row.amount;
}
function importRow(row: Row): Outcome {
try {
validate(row);
const saved = save(row);
return { status: "saved", ref: row.ref, amount: saved };
} catch (caught) {
if (caught instanceof ValidationFault) {
return { status: "validation", ref: row.ref, message: caught.message };
}
if (caught instanceof SaveFault) {
return { status: "save", ref: row.ref, message: caught.message };
}
throw toError(caught);
}
}
function pad(text: string, width: number): string {
const gap = width - text.length;
return text + " ".repeat(gap > 0 ? gap : 0);
}
const ROWS: Row[] = [
{ ref: "r1", email: "a@x.io", amount: 120 },
{ ref: "r2", email: "b@x.io", amount: 0 },
{ ref: "x3", email: "c@x.io", amount: 40 },
{ ref: "r4", email: "", amount: 90 },
{ ref: "r5", email: "d@x.io", amount: 30 }
];
const outcomes = ROWS.map(importRow);
let loaded = 0;
let total = 0;
console.log("rows: " + outcomes.length);
console.log(pad("REF", 6) + pad("STATUS", 12) + "AMOUNT");
for (const o of outcomes) {
if (o.status === "saved") {
loaded++;
total += o.amount;
console.log(pad(o.ref, 6) + pad("saved", 12) + o.amount);
} else {
console.log(pad(o.ref, 6) + pad(o.status, 12) + "--");
}
}
console.log("loaded: " + loaded + ", total: " + total);
Output:
rows: 5
REF STATUS AMOUNT
r1 saved 120
r2 validation --
x3 save --
r4 validation --
r5 saved 30
loaded: 2, total: 150
Trace the five rows in order. Row r1 has a real email and a positive amount, so it validates, saves, and reports saved with 120. Row r2 fails on the amount <= 0 check, so validate throws a ValidationFault, the catch narrows it, and the outcome is validation. Row x3 validates cleanly but its ref begins with x, so save throws a SaveFault and the outcome is save. Row r4 has a blank email and fails validation. Row r5 is clean and saves 30. Only the two saved rows contribute to the total, so loaded is 2 and total is 120 + 30 = 150.
The value of this shape is that the two known faults never leave the row. Each is caught, identified by instanceof, and folded into the Outcome union, so the caller receives a plain array of results and the report loop never touches a try. The Outcome union is doing the same work the SubmitState union did earlier: a row that failed carries a message and no amount, and a saved row carries an amount and no message, so the impossible combinations cannot be constructed.
The rethrow line is the honest part. throw toError(caught) fires only when the caught value is neither of the two faults the importer understands, which means a genuinely unexpected error, a bug in validate, an out-of-memory, is never quietly folded into a tidy Outcome and hidden. It is normalised to an Error and pushed up the stack where someone can see it.
That same rethrow is also the design's main flaw, and it is worth being blunt about. Because the rows are processed with ROWS.map(importRow), a single rethrow aborts the whole map and discards every outcome already computed, so one unexpected error loses the good rows with it; a production importer would collect unexpected errors into a fourth Outcome variant, or return a Result per row, rather than let one bad row sink the batch. Two smaller limitations sit alongside it: save uses ref.startsWith("x") as a deterministic stand-in for what is really an I/O failure, so it cannot model the transient, retryable failures that a real ledger produces; and because validate and save only ever throw the two known fault types, the rethrow branch is never exercised by this sample data, which means the very path that matters most in production is the one the example cannot demonstrate.
Common Mistakes
- Reading
error.messagestraight off the caught value. The catch variable isunknownunder strict mode, soerror.messagewill not compile until you narrow withinstanceof Erroror a type guard. - Annotating
catch (error: any)to silence the compiler. This throws away the exact protectionunknownwas added to give you, and hands you back the runtime crash the change was designed to prevent. - Writing
catch (error: Error). It is a syntax error: a catch clause annotation may only beanyorunknown, never a specific type, because the runtime can throw anything. - Swallowing failures in an empty
catch {}. A real error becomes a silent mystery; the operation looks like it succeeded when it did not, and nobody finds out until much later. - Not rethrowing what you cannot handle. If your catch only knows two error kinds, an unrelated bug that reaches it will be mistreated as one of them unless you
throw caughton the unrecognised path. - Leaving off
awaitintry { doAsync() }. The promise rejection escapes thetryblock entirely and becomes an unhandled rejection, because thetryfinished before the promise settled. - Awaiting inside
.forEach.forEachignores the returned promises, so the loop completes instantly and every rejection inside it goes unhandled; use afor...ofloop instead. - Writing
return op()in atry/finallythat must clean up after the result. Withoutreturn await op(), thefinallyruns before the operation settles, releasing the resource too early. - Subclassing
Errorwithoutthis.name, or withoutObject.setPrototypeOfon ES5 targets. The first gives useless log labels; the second makesinstanceof YourErrorsilently returnfalse.
Best Practices
- Keep
useUnknownInCatchVariableson and narrow every caught value. It ships withstrict; treat theunknowncatch type as a feature that forces you to prove what you have before you use it. - Write one
toError(value: unknown): Errorhelper and call it at every logging site. Normalise at the boundary so everything downstream sees a uniformErrorwith a real.message. - Subclass
Error, setthis.name, and add areadonly kindliteral. The discriminant turns your error classes into a union yourswitchcan narrow exhaustively. - Rethrow anything you do not recognise with
if (!isAppError(e)) throw e. Handle the errors you understand and let the rest bubble to where they can be seen. - Use
Result<T, E>for expected, recoverable failures andthrowfor bugs. Put the failures the caller must handle into the signature, and leave the unrecoverable ones to the exception path. - Prefer
return await op()insidetry/finally. It keeps the cleanup ordered after the operation settles rather than before. - Attach a global
unhandledrejectionorprocess.on("unhandledRejection")handler. Treat it as a last-resort safety net that logs and alerts, not as your actual error-handling plan. - Log the operation, its inputs, and a request id alongside the error. A bare
error.messagewith no context is far harder to act on than a message tied to what was being attempted.
Practice Exercises
- The Narrowing. Write a single
catchblock that handles anError, astring, and everything else in three distinct branches, then throw each of the three kinds at it and confirm the correct branch runs for each. - The Error Hierarchy. Create
NotFoundErrorandRateLimitError(the latter carryingretryAfter: number) withreadonly kinddiscriminants, then write aswitchin whichretryAfteris reachable in exactly one branch and the compiler proves the switch is exhaustive. - The Result. Convert an async function that throws into one returning
Promise<Result<T>>, and verify the compiler blocks access to.valueuntil you have checked.okon the returned object. - The Cleanup Order. Write a
withLockhelper usingtry/finallythat logsacquire, then the operation, thenrelease, and prove that switchingreturn await op()toreturn op()reorders the log soreleaseprints before the operation finishes.