Sub topic 7
Catching Errors Selectively with instanceof
This chapter assumes you know try/catch, async/await, and the HttpError and NotFoundError classes from the previous chapter. The topic is deciding, inside one catch block, which errors to handle and which to let through.
Why one catch block needs to branch
A catch clause in JavaScript catches everything. Unlike Java or C#, there is no catch (NotFoundError e) syntax. Inside the block, you check the error's type yourself. The instanceof operator does this. It walks the prototype chain of the thrown value and returns true if it finds the given class's prototype anywhere along that chain.
Because a subclass instance is also an instance of its parent, instanceof matches whole groups of errors. A NotFoundError passes both instanceof NotFoundError and instanceof HttpError.
A complete example
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';
}
}
async function deleteUser(id) {
if (id === 42) throw new NotFoundError(`User ${id}`);
if (id === 7) throw new HttpError(503, 'Service unavailable');
if (id === 0) null.delete(); // a real bug: TypeError
}
async function handleDelete(id) {
try {
await deleteUser(id);
console.log(`Deleted ${id}`);
} catch (err) {
if (err instanceof NotFoundError) {
console.warn(err.message);
} else if (err instanceof HttpError) {
console.error(`Request failed with status ${err.status}`);
} else {
throw err;
}
}
}
await handleDelete(42); // User 42 not found
await handleDelete(7); // Request failed with status 503
await handleDelete(1); // Deleted 1
await handleDelete(0).catch((e) => console.log('Escaped:', e.name)); // Escaped: TypeErrorSave this as handle.mjs and run it with node handle.mjs. The .mjs extension turns on top-level await.
The rules that matter
- Check the most specific class first. If
HttpErrorcame first, it would also catch everyNotFoundError, and theNotFoundErrorbranch would never run. - Always rethrow what you don't recognize. The final
else { throw err; }keeps bugs like theTypeErrorabove from being swallowed. Acatchblock that handles everything hides real defects. - Built-in types work the same way.
err instanceof TypeErrororerr instanceof SyntaxError(fromJSON.parse) are valid branches.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Parent class checked before child | Child branch never runs | Order checks from specific to general |
| No final rethrow | Unexpected bugs vanish silently | End with `else { throw err; }` |
| Matching on `err.message` text | Breaks when the wording changes | Match on class or a `code` field |
| Assuming `err` is an `Error` | `err.message` is `undefined` for `throw 'oops'` | Any value can be thrown; the rethrow branch covers it |
Exercise
A teammate writes catch (err) { if (err instanceof HttpError) {...} else if (err instanceof NotFoundError) {...} } with no else branch. Name the two problems.
Show answer
First, the NotFoundError branch can never run, because every NotFoundError is also an HttpError and the first check catches it. Second, without a final else that rethrows, any other error, such as a TypeError from a bug, is silently swallowed.
Exercise
Add a branch to handleDelete that logs "Bad input" for TypeError while still rethrowing everything else. Where does it go?
Show answer
Put else if (err instanceof TypeError) { console.error('Bad input'); } after the HttpError check and before the final else { throw err; }. TypeError is not related to HttpError, so its position relative to the HttpError check doesn't affect correctness. It must come before the rethrow.