Sub topic 7
Handling Only What You Understand: instanceof and Rethrowing
This chapter assumes you know how try and catch work, how to throw errors, and how to define a custom error class that extends Error. It also assumes you can run scripts in Node.js, because some examples use the node:fs module.
A catch block catches everything thrown inside its try block. That includes the failure you expected, but also typos, null dereferences, and bugs in code you never meant to guard. This chapter shows how to look at a caught error, handle it only if you understand it, and send everything else back up the call stack.
The Problem with Catching Everything
Here is a function that loads a user's saved settings and falls back to defaults when the data is missing or broken:
function loadSettings(text) {
try {
const settings = JSON.parse(text);
return { theme: settings.theme.toLowerCase() };
} catch (err) {
return { theme: 'light' };
}
}
console.log(loadSettings('{"theme": "DARK"}')); // { theme: 'dark' }
console.log(loadSettings('not json')); // { theme: 'light' }
console.log(loadSettings('{}')); // { theme: 'light' }The third call looks fine but hides a bug. settings.theme is undefined, so .toLowerCase() throws a TypeError. The catch block can't tell that apart from a SyntaxError produced by bad JSON, so it treats both the same way. If someone later renames theme to colorTheme in the saved data, every user silently gets the light theme and no error ever shows up.
A catch-all catch like this one is often called "swallowing" errors. It turns loud, easy-to-find bugs into quiet wrong behavior.
The Pattern: Check, Handle, Rethrow
The fix is to check what you caught. If it is the failure you planned for, handle it. If not, throw it again so that someone else, or a global handler, can deal with it.
function loadSettings(text) {
try {
const settings = JSON.parse(text);
return { theme: settings.theme.toLowerCase() };
} catch (err) {
if (err instanceof SyntaxError) {
return { theme: 'light' };
}
throw err;
}
}
console.log(loadSettings('not json')); // { theme: 'light' }
loadSettings('{}'); // throws TypeError: Cannot read properties of undefinedNow bad JSON still falls back to defaults, but the TypeError escapes and shows you exactly where the bug is.
Rethrowing keeps the original stack
throw err does not create a new error. It throws the same object again, so err.stack still points to the line where the error was first created, not to the throw err line. That is what you want: the stack trace leads to the real cause.
function inner() {
null.length; // TypeError created here
}
function outer() {
try {
inner();
} catch (err) {
if (err instanceof RangeError) return 0;
throw err;
}
}
try {
outer();
} catch (err) {
console.log(err.stack.split('\n')[1].trim()); // at inner (...)
}If you want to add context, such as "failed while loading settings", wrap the error instead of replacing it. The next chapter covers the cause option for that.
Narrowing with instanceof
err instanceof SomeClass is true when SomeClass.prototype appears anywhere in the error's prototype chain. That means it matches subclasses too. With custom error classes this matters for the order of your checks.
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';
this.resource = resource;
}
}
function describe(err) {
if (err instanceof NotFoundError) {
return `Missing: ${err.resource}`;
}
if (err instanceof HttpError) {
return `Server said ${err.status}`;
}
throw err;
}
console.log(describe(new NotFoundError('user 7'))); // Missing: user 7
console.log(describe(new HttpError(503, 'Unavailable'))); // Server said 503Check the most specific class first. If you swapped the two if blocks, every NotFoundError would match HttpError first, and the 404 branch would never run.
Other Ways to Identify an Error
instanceof is not always the best tool. Many errors share one class and differ only in a property, and some environments break instanceof entirely.
Checking a code property
Node.js reports system failures as plain Error objects with a string code property. To treat a missing file as "no data" while still surfacing permission problems and other failures, check err.code:
const fs = require('node:fs');
function readOptionalFile(path) {
try {
return fs.readFileSync(path, 'utf8');
} catch (err) {
if (err.code === 'ENOENT') {
return null; // file does not exist: that's fine
}
throw err; // EACCES, EISDIR, and anything else
}
}
console.log(readOptionalFile('./does-not-exist.txt')); // nullCodes stay stable across versions, while messages are meant for people and can change wording. Never branch on err.message.
When instanceof gives the wrong answer
instanceof compares against one specific constructor object, and two situations can produce two copies of the "same" class:
- Different realms. A realm is a separate global environment, such as an iframe, a Web Worker, or a Node.js
vmcontext. ATypeErrorcreated in an iframe isn'tinstanceof TypeErrorin the parent page, because each realm has its ownTypeErrorconstructor. - Duplicate packages. If your
node_modulesholds two versions of a library, errors thrown by one copy won't match the class you imported from the other.
In those cases, checking err.name or a library-defined code works better, because those are plain strings. This is one reason custom error classes should set this.name.
| Check | Good for | Weakness |
|---|---|---|
| `err instanceof Cls` | Your own classes and built-ins in one realm | Fails across realms and duplicate packages; matches subclasses |
| `err.name === 'X'` | Cross-realm checks, simple classes | Exact match only; no subclass matching; depends on name being set |
| `err.code === 'X'` | Node.js system errors, library errors | Only exists if the thrower sets it |
| `err.message` text | Nothing; avoid it | Wording changes, localization |
Not Everything Thrown Is an Error
JavaScript lets you throw any value: throw 'oops', throw 42, or throw { status: 500 }. Third-party code sometimes does this. Then err.message and err.stack are undefined, and reading err.code on a thrown null throws a new TypeError from inside your catch block.
A defensive handler checks what kind of value it has before reading properties:
function toMessage(err) {
if (err instanceof Error) return err.message;
return `Non-error thrown: ${String(err)}`;
}
try {
throw 'disk full';
} catch (err) {
console.log(toMessage(err)); // Non-error thrown: disk full
}In your own code, always throw Error objects or subclasses so callers get a message and a stack.
Keep the try Block Small
Narrowing in catch works best with a narrow try. The more code a try block wraps, the more chances an unrelated error has of matching your check by accident. In the first loadSettings example, only JSON.parse can produce the SyntaxError we planned for, so only that call needs guarding:
function loadSettings(text) {
let settings;
try {
settings = JSON.parse(text);
} catch (err) {
if (err instanceof SyntaxError) return { theme: 'light' };
throw err;
}
// Errors below here are bugs and propagate normally.
return { theme: settings.theme.toLowerCase() };
}The rethrow line looks unreachable, since JSON.parse on a string only throws SyntaxError. Keep it anyway. If text were an object whose toString method throws, a different error would come out, and the rethrow makes sure it isn't hidden.
Common Mistakes
- Forgetting the rethrow. An
ifwith noelseand nothrow errafter it quietly swallows every unmatched error. The function then returnsundefined. - Logging and rethrowing at every level. If each layer runs
console.error(err)and thenthrow err, one failure prints five times. Log at the place that finally handles the error. - Throwing a new error that drops the original.
throw new Error('Load failed')loses the original stack and type. Rethrow the original, or wrap it withcause. - Checking a parent class before its subclass. The specific branch never runs.
- Matching on message text. It breaks the first time someone fixes a typo in the message.
Exercise
This function should return 0 when the input is out of range, but it also hides a bug. Find the bug and rewrite the catch block so that only the intended case is handled. function safeRepeat(str, count) { try { return str.repaet(count); } catch (err) { return ''; } } (String.prototype.repeat throws a RangeError for negative counts.)
Show answer
The typo repaet makes str.repaet undefined, so calling it throws a TypeError on every call, and the catch-all turns that into an empty string every time. Fix the typo, then narrow the catch: catch (err) { if (err instanceof RangeError) return ''; throw err; }. With the narrowed catch in place, the typo would have shown up right away as an uncaught TypeError.
Exercise
An app catches errors from a payment library and checks err instanceof CardDeclinedError, using the class imported from the library. The check worked in testing but returns false in production, even though err.name is 'CardDeclinedError'. What is a likely cause, and what check would you use instead?
Show answer
Production probably has two copies of the library installed, for example two versions in node_modules, so the error was built with a different CardDeclinedError constructor than the one the app imported. instanceof compares against one specific constructor, so it fails. Check a string instead, such as err.name === 'CardDeclinedError' or a library-provided err.code, which match no matter which copy created the error.
Exercise
Given classes ValidationError extends Error and EmailError extends ValidationError, in what order should a catch block test them, and why?
Show answer
Test EmailError first, then ValidationError, then rethrow. An EmailError is also an instance of ValidationError, so checking ValidationError first would catch email errors in the general branch, and the email-specific branch would never run.