Sub topic 5
The Built-in Error Types
This chapter assumes you know how to read an Error's name and message, how to use throw, and how to catch errors with try and catch. Those topics come from the earlier chapters.
When JavaScript itself detects a problem, it does not throw a plain Error. It throws one of several more specific types. Each type tells you which kind of mistake happened, so you can start debugging before you finish reading the message.
The family tree
Every built-in error type is a subclass of Error. Each one inherits message and stack and sets its own name.
Because each type inherits from Error, a check such as err instanceof Error is true for all of them.
What each type means
| Type | Thrown when | Typical trigger |
|---|---|---|
| `TypeError` | A value is not the kind the operation needs | `null.length`, calling a non-function |
| `RangeError` | A number is outside the allowed range | `new Array(-1)`, `(1).toFixed(200)` |
| `SyntaxError` | Text cannot be parsed as code or data | `JSON.parse('{bad}')` |
| `ReferenceError` | A variable name does not exist | Using an undeclared variable |
| `URIError` | A URI function gets malformed input | `decodeURIComponent('%')` |
| `EvalError` | Kept for backward compatibility | Modern engines never throw it |
| `AggregateError` | Several errors are reported together | `Promise.any` when every promise rejects |
TypeError is the one you will see most. "Cannot read properties of undefined" is a TypeError, and it usually means a value you expected to be an object turned out to be missing.
Seeing them in action
The script below triggers five of the types and prints the name of each one. You can run it with Node.js or paste it into a browser console.
const attempts = [
() => null.length,
() => new Array(-1),
() => JSON.parse('{bad}'),
() => notDeclaredAnywhere,
() => decodeURIComponent('%'),
];
for (const run of attempts) {
try {
run();
} catch (err) {
console.log(`${err.name}: ${err.message}`);
console.log(' is an Error?', err instanceof Error);
}
}The output looks like this, though the exact wording varies by engine:
TypeError: Cannot read properties of null (reading 'length')
is an Error? true
RangeError: Invalid array length
is an Error? true
SyntaxError: Expected property name or '}' in JSON at position 1
is an Error? true
ReferenceError: notDeclaredAnywhere is not defined
is an Error? true
URIError: URI malformed
is an Error? trueA SyntaxError has two different sources
A SyntaxError in your own source code is raised while the script is being parsed, before any line of it runs. A try block in the same file cannot catch it, because the whole file fails to load. You can only catch a SyntaxError that is raised at run time, for example by JSON.parse, new Function(...), or new RegExp('[').
Throwing built-in types yourself
You can throw the built-in types from your own code. Pick the one whose meaning matches the problem, and callers will get a familiar signal.
function setVolume(level) {
if (typeof level !== 'number') {
throw new TypeError(`level must be a number, got ${typeof level}`);
}
if (level < 0 || level > 100) {
throw new RangeError(`level must be 0-100, got ${level}`);
}
return level;
}
try {
setVolume(150);
} catch (err) {
console.log(err.name); // RangeError
}AggregateError holds a list
AggregateError adds an errors array that holds the individual failures.
const agg = new AggregateError(
[new Error('mirror A down'), new Error('mirror B down')],
'All mirrors failed'
);
console.log(agg.message); // All mirrors failed
console.log(agg.errors.map((e) => e.message)); // [ 'mirror A down', 'mirror B down' ]When none of the built-in types describes your domain's failures, such as a failed validation, you can define your own type. The next chapter covers that.
Exercise
Which error type does each line throw: (a) undefined(), (b) 'abc'.repeat(-1), (c) JSON.parse(''), (d) console.log(missingVar)?
Show answer
(a) TypeError, because undefined is not a function. (b) RangeError, because the repeat count must be non-negative. (c) SyntaxError, because an empty string is not valid JSON. (d) ReferenceError, because missingVar is not declared.
Exercise
A file contains try { let x = ; } catch (e) { console.log('caught'); }. Why does "caught" never print?
Show answer
The invalid code is a parse-time SyntaxError. The engine rejects the whole script before running it, so the try block never runs and cannot catch the error.