Sub topic 2
The Built-in Error Types
This chapter assumes you already know how throw, try, and catch work, and that you are comfortable with classes and basic promises.
The Built-in Error Types
JavaScript throws different subclasses of Error for different problems. The name property tells you which one you got.
| Type | Typical cause |
|---|---|
| `TypeError` | Calling a non-function, or reading a property of `undefined` |
| `RangeError` | A value outside its allowed range, such as `new Array(-1)` |
| `SyntaxError` | Invalid code, or invalid input to `JSON.parse` |
| `ReferenceError` | Using a variable that was never declared |
Defining Your Own Error Classes
When you extend Error, your error can carry extra data. Set name so that logs show the right type.
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
function validateAge(age) {
if (!Number.isInteger(age) || age < 0) {
throw new ValidationError('Age must be a non-negative integer', 'age');
}
return age;
}
try {
validateAge(-1);
} catch (err) {
if (err instanceof ValidationError) {
console.log(`${err.field}: ${err.message}`);
} else {
throw err;
}
}Handling Only What You Understand: instanceof and Rethrowing
A catch block catches everything, including bugs such as a misspelled variable. In the example above, instanceof checks for the one type the code knows how to handle, and every other error is rethrown. If you swallow errors you don't understand, real bugs get hidden.
Optional catch Binding
Since ES2019, you can leave out the error variable when you don't need it:
function isValidJson(text) {
try {
JSON.parse(text);
return true;
} catch {
return false;
}
}
console.log(isValidJson('[1, 2]')); // true
console.log(isValidJson('{oops}')); // falseAdding Context with the cause Option
When you rethrow an error with a clearer message, pass the original error as cause (ES2022). The original error and its stack stay attached to the new one.
function loadConfig(text) {
try {
return JSON.parse(text);
} catch (err) {
throw new Error('Config file is not valid JSON', { cause: err });
}
}
try {
loadConfig('nope');
} catch (err) {
console.log(err.message); // Config file is not valid JSON
console.log(err.cause.name); // SyntaxError
}Why try/catch Misses Errors in Later Callbacks
A try block only covers code that runs while the block is executing. A callback scheduled with setTimeout runs after the block has finished, so nothing catches its error:
try {
setTimeout(() => {
throw new Error('boom');
}, 0);
} catch (err) {
console.log('This never runs');
}Exercise
A catch block logs "Invalid input" for every error it receives. What goes wrong, and how do you fix it?
Show answer
Unrelated bugs, such as a TypeError from a typo, are also reported as "Invalid input", which hides them. Check the expected type with instanceof, handle only that type, and rethrow everything else.
Exercise
How do you keep the original SyntaxError when you throw a more descriptive error?
Show answer
Pass it as the cause: throw new Error('message', { cause: err }). You can read it later from err.cause.