Sub topic 7
Handling Only What You Understand: instanceof and Rethrowing
This chapter assumes you know how try/catch works and how to define a custom error class that extends Error. Both topics were covered in earlier chapters.
A catch block catches everything thrown inside its try. That includes errors you expected, like invalid user input. It also includes errors you didn't expect, like a typo that causes a TypeError. If you treat every error the same way, you can hide real bugs behind a friendly "please try again" message.
The fix is to narrow. Check what you caught, handle the cases you understand, and rethrow the rest.
The Problem with Catching Everything
Here is a function that seems to handle invalid input:
function parseQuantity(input) {
const n = Number(input.trim());
if (!Number.isInteger(n) || n < 1) {
throw new Error('Quantity must be a positive integer');
}
return n;
}
try {
parseQuantity(undefined);
} catch (err) {
console.log('Please enter a valid quantity.');
}The user sees "Please enter a valid quantity." The real cause is different. input.trim() threw a TypeError because input was undefined, which points to a bug in the calling code. The catch block hid it.
Narrowing with instanceof
err instanceof SomeClass is true when SomeClass.prototype appears in the error's prototype chain. Because custom errors extend Error, this check works for your own classes as well as the built-in ones.
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
function parseQuantity(input) {
const n = Number(input.trim());
if (!Number.isInteger(n) || n < 1) {
throw new ValidationError('Quantity must be a positive integer', 'quantity');
}
return n;
}
function handleForm(input) {
try {
return parseQuantity(input);
} catch (err) {
if (err instanceof ValidationError) {
console.log(`${err.field}: ${err.message}`);
return null;
}
throw err; // not ours to handle
}
}
handleForm('0'); // logs "quantity: Quantity must be a positive integer"
handleForm(undefined); // TypeError propagates to the callerThe throw err line is the rethrow. It passes the original error object up unchanged, with its stack trace intact. Code higher up, or a global handler, can then report it as the bug it is.
Handling Several Types
Order your checks from most specific to most general. A subclass instance also passes instanceof for its parent class, so a parent check placed first would catch everything meant for the subclass.
class NotFoundError extends Error {
constructor(message) {
super(message);
this.name = 'NotFoundError';
}
}
function describe(err) {
if (err instanceof NotFoundError) return 'missing';
if (err instanceof RangeError) return 'out of range';
if (err instanceof Error) return 'other error';
return 'non-Error value';
}
console.log(describe(new NotFoundError('x'))); // 'missing'
console.log(describe(new RangeError('x'))); // 'out of range'
console.log(describe('a string')); // 'non-Error value'The last branch is there because JavaScript lets you throw any value, including strings and plain objects. Don't assume that err.message exists.
Common Mistakes
| Mistake | Effect | Fix |
|---|---|---|
| No rethrow in the fallback branch | Unknown errors are silently swallowed | End with `throw err` |
| `throw new Error(err.message)` | Loses the original type and stack | Rethrow `err` itself, or wrap it using `cause` |
| Parent class checked before subclass | Subclass branch never runs | Put the most specific checks first |
| Matching on `err.message` text | Breaks when the wording changes | Check the class or a `code` property |
Exercise
A function catches errors from loadSettings(). It should return default settings when a NotFoundError is thrown, and let every other error propagate. Write the catch block.
Show answer
catch (err) { if (err instanceof NotFoundError) { return { theme: 'light' }; } throw err; }. The instanceof check handles only the expected case, and throw err passes everything else to the caller with its type and stack unchanged.
Exercise
Why does putting if (err instanceof Error) before if (err instanceof ValidationError) break the handler?
Show answer
ValidationError extends Error, so every ValidationError also passes the Error check. The first branch catches it, and the ValidationError branch never runs.