Sub topic 7
Catching Errors Selectively with instanceof
A single catch block receives every error thrown inside its try, whatever the reason. Real code usually wants to handle some errors and let the rest propagate. A missing record might become a warning, while a broken database connection should still crash the request. This chapter shows how to use instanceof to sort caught errors by class, which order to check them in, and where instanceof gives the wrong answer.
The chapter assumes you know ES2015 classes, try/catch, and async/await. It also uses the HttpError and NotFoundError classes from the previous chapter on error hierarchies.
How instanceof Decides
value instanceof C walks the prototype chain of value. At each step it compares the current prototype with C.prototype. If one matches, the result is true. If the chain ends at null without a match, the result is false.
A NotFoundError has this chain:
So err instanceof NotFoundError, err instanceof HttpError, and err instanceof Error are all true. A subclass instance matches every ancestor class, and this fact drives most of the rules below.
Two more details are useful:
instanceofwith a primitive on the left always returnsfalseand never throws.'oops' instanceof Errorisfalse. That makes it safe to use on acatchparameter, which can hold any value.- The check depends on the prototype chain only. Property values play no part. An object with
name: 'NotFoundError'is not aNotFoundErrorunless its prototype chain says so.
The Basic Pattern: Specific First, Rethrow the Rest
This is a complete, runnable example. Save it as handle.mjs and run it with node handle.mjs.
class HttpError extends Error {
constructor(status, message, options) {
super(message, options);
this.name = 'HttpError';
this.status = status;
}
}
class NotFoundError extends HttpError {
constructor(resource, options) {
super(404, `${resource} not found`, options);
this.name = 'NotFoundError';
}
}
const users = new Map([[1, { id: 1, name: 'Ada' }]]);
async function deleteUser(id) {
if (typeof id !== 'number') {
throw new TypeError(`id must be a number, got ${typeof id}`);
}
if (id < 0) {
throw new HttpError(400, 'id must not be negative');
}
if (!users.has(id)) {
throw new NotFoundError(`User ${id}`);
}
users.delete(id);
}
async function handleDelete(id) {
try {
await deleteUser(id);
console.log(`Deleted ${id}`);
} catch (err) {
if (err instanceof NotFoundError) {
console.warn(`Warning: ${err.message}`);
} else if (err instanceof HttpError) {
console.error(`Request failed with status ${err.status}`);
} else {
throw err;
}
}
}
await handleDelete(1); // Deleted 1
await handleDelete(42); // Warning: User 42 not found
await handleDelete(-5); // Request failed with status 400
try {
await handleDelete('abc');
} catch (err) {
console.log(`Escaped to caller: ${err.name}`); // Escaped to caller: TypeError
}The catch block follows three rules.
- Check the most specific class first.
NotFoundErrorcomes beforeHttpError. - Handle only what you understand. Each branch does something useful with that kind of error.
- Rethrow everything else. The final
else { throw err; }lets theTypeError, which is a programming bug, reach a caller that can report it.
Common Mistake: Wrong Order
A subclass instance also matches its parent class, so a general check placed first catches everything below it:
class HttpError extends Error {
constructor(status, message) {
super(message);
this.name = 'HttpError';
this.status = status;
}
}
class NotFoundError extends HttpError {
constructor(resource) {
super(404, `${resource} not found`);
this.name = 'NotFoundError';
}
}
function classify(err) {
if (err instanceof HttpError) return 'http'; // catches NotFoundError too
if (err instanceof NotFoundError) return 'missing'; // never reached
return 'other';
}
console.log(classify(new NotFoundError('Order 7'))); // 'http'No error or warning appears. The NotFoundError branch simply never runs. When you add a subclass, check every catch block that tests for its parent.
Common Mistake: Swallowing Unknown Errors
This version looks harmless:
try {
await deleteUser(id);
} catch (err) {
if (err instanceof NotFoundError) {
console.warn(err.message);
}
}Without an else, every other error disappears without a trace. That includes a TypeError from a typo or a RangeError from bad input. The function returns normally, and the caller thinks the delete succeeded. Always end the chain with throw err unless swallowing every remaining error is a deliberate, documented choice.
Built-in Types Work the Same Way
The built-in types are ordinary subclasses of Error, so you test them the same way:
function parseSettings(text) {
try {
return JSON.parse(text);
} catch (err) {
if (err instanceof SyntaxError) {
return {}; // bad JSON: fall back to defaults
}
throw err;
}
}
console.log(parseSettings('{"theme":"dark"}')); // { theme: 'dark' }
console.log(parseSettings('{oops')); // {}Be careful with built-in types. A TypeError can come from your validation code, but it can also come from calling undefined as a function. If you catch TypeError broadly, you may hide real bugs. Your own subclasses avoid this problem because only your code throws them.
Selective Handling with Promises
With .catch(), the same rules apply. Rethrowing inside the callback rejects the returned promise again:
deleteUser(42)
.catch((err) => {
if (err instanceof NotFoundError) return null; // treat as already deleted
throw err; // keep the rejection
})
.then((result) => console.log('Result:', result));If you forget the throw err, the callback returns undefined and every failure turns into a success.
Alternatives to instanceof
instanceof is not the only way to tell errors apart. The table compares the usual options.
| Check | Example | Strengths | Weaknesses |
|---|---|---|---|
| `instanceof` | `err instanceof NotFoundError` | Matches subclasses; safe on any value | Fails across realms and with duplicate package copies |
| `name` string | `err?.name === 'NotFoundError'` | Works across realms | Exact match only, ignores hierarchy; any object can fake it |
| `code` property | `err?.code === 'ENOENT'` | Stable, works after serialization | Needs a documented code list; no hierarchy |
Node.js system errors are the main case for code. A failed readFile throws a plain Error with code: 'ENOENT', so instanceof cannot tell file-not-found apart from permission-denied. Use the code there:
import { readFile } from 'node:fs/promises';
async function readOptional(path) {
try {
return await readFile(path, 'utf8');
} catch (err) {
if (err?.code === 'ENOENT') return null;
throw err;
}
}
console.log(await readOptional('./does-not-exist.txt')); // nullThe optional chaining (err?.code) matters because the catch parameter could be null or undefined if someone wrote throw null.
When instanceof Lies: Realms and Duplicate Classes
instanceof compares object identity with one specific C.prototype. If an error was created with a different copy of the class, the check fails even though the class name and code are the same.
That happens in two common situations:
- Different realms. Each iframe, worker, and Node
vmcontext has its own set of built-in constructors. - Duplicate packages. If
node_modulescontains two versions of a library, each one defines its ownNotFoundError.
The realm case is easy to see in Node:
import vm from 'node:vm';
const foreign = vm.runInNewContext('new TypeError("from another realm")');
console.log(foreign instanceof TypeError); // false
console.log(foreign instanceof Error); // false
console.log(foreign.name); // 'TypeError'
console.log(Object.prototype.toString.call(foreign)); // '[object Error]'Object.prototype.toString reads an internal marker that every real Error carries, so it works across realms. It cannot tell subclasses apart, though. For errors that cross package or realm boundaries, add a code property and check it as well as instanceof, or instead of it. A later chapter covers a third case: code compiled to ES5, where instanceof fails for custom subclasses unless you repair the prototype.
Exercise
A catch block checks err instanceof Error first, then err instanceof HttpError, then err instanceof NotFoundError. A NotFoundError is thrown. Which branch runs, and how should you fix the block?
Show answer
The Error branch runs, because a NotFoundError's prototype chain includes Error.prototype. Reorder the checks from most specific to least specific: NotFoundError, then HttpError, then Error (or a final rethrow). The other two branches are unreachable in the original order.
Exercise
Your service catches errors from a third-party library with err instanceof RateLimitError, using the class imported from that library. The check passes in unit tests but fails in production, even though the logged name is 'RateLimitError'. Give a likely cause and a fix.
Show answer
Production probably loads two copies of the library, for example two versions in nodemodules. The thrown error comes from one copy and the imported class from the other, so their prototypes are different objects. Fix the duplicate install by deduplicating or pinning the version. For a check that does not depend on module identity, test a stable property such as `err?.code === 'RATELIMIT' or err?.name === 'RateLimitError'`.
Exercise
Rewrite this handler so that it no longer hides unexpected failures: promise.catch((err) => { if (err instanceof NotFoundError) return null; }).
Show answer
Add a rethrow for everything else: promise.catch((err) => { if (err instanceof NotFoundError) return null; throw err; }). Without the rethrow, the callback returns undefined for every other error, and the rejection turns into a fulfilled promise.