Sub topic 2
The Built-in Error Types
This chapter assumes you know JavaScript functions, ES2015 classes, throw and try/catch, and how to run code in Node.js or a browser console. You should also know the name, message, and stack properties from the previous chapter.
Before you write your own error classes, it helps to know the ones JavaScript already has. The language defines a small family of error constructors. The engine throws them when your code breaks a rule, and you can throw them yourself when they fit. Your custom classes will follow the same pattern, so the built-ins work as a reference design.
The Family at a Glance
Every standard error type is a constructor that inherits from Error. Each one marks a different kind of failure.
| Constructor | Typical trigger from the engine | Throw it yourself when |
|---|---|---|
| `Error` | Rarely thrown directly by the engine | Nothing more specific fits |
| `TypeError` | Reading a property of `null` or `undefined`, calling a non-function, assigning to a read-only property in strict mode | An argument has the wrong type or shape |
| `RangeError` | `new Array(-1)`, `(1).toFixed(101)`, exceeding the call stack in V8 | A value has the right type but is outside the allowed range |
| `SyntaxError` | Invalid source code, `JSON.parse('{bad')`, `new RegExp('(')` | You are writing a parser and the input is malformed |
| `ReferenceError` | Using an undeclared variable, or reading a `let`/`const` variable before its declaration runs | Almost never |
| `URIError` | `decodeURIComponent('%')` | Almost never |
| `EvalError` | Not thrown by the current specification | Never; it exists for backward compatibility |
| `AggregateError` | `Promise.any` when every promise rejects | You need to report several failures at once (covered in a later chapter) |
Some engines add non-standard types. Firefox has InternalError for cases such as "too much recursion", where V8 throws a RangeError instead. Don't write code that depends on these.
How the Built-ins Are Wired Together
Each built-in error type has two prototype links. The constructor's own prototype is Error, so static members are inherited. The constructor's .prototype object inherits from Error.prototype, so instances get toString and the rest of the shared behavior.
You can confirm this structure in a console:
const e = new TypeError('bad input');
console.log(Object.getPrototypeOf(TypeError) === Error); // true
console.log(Object.getPrototypeOf(TypeError.prototype) === Error.prototype); // true
console.log(e instanceof TypeError); // true
console.log(e instanceof Error); // true
console.log(e instanceof RangeError); // falseWhere `name` and `message` live
The name is not stored on each instance. It is a property of the constructor's prototype, and every instance inherits it. The message becomes an own property only when you pass one.
const withMessage = new TypeError('bad input');
const noMessage = new TypeError();
console.log(Object.hasOwn(TypeError.prototype, 'name')); // true
console.log(TypeError.prototype.name); // 'TypeError'
console.log(Object.hasOwn(withMessage, 'name')); // false
console.log(Object.hasOwn(withMessage, 'message')); // true
console.log(Object.hasOwn(noMessage, 'message')); // false
console.log(JSON.stringify(noMessage.message)); // '""' (inherited from Error.prototype)
console.log(String(withMessage)); // 'TypeError: bad input'This matters for the next two chapters. A class you write with extends Error gets a correct prototype chain automatically. It does not get its own name, though. It inherits 'Error' unless you set one. The built-ins avoid that problem by putting name on each prototype.
Calling without `new`
Error constructors work the same with or without new. TypeError('x') returns a new TypeError, just as new TypeError('x') does. Class-based custom errors can't do this, because calling a class without new throws a TypeError. Use new everywhere so built-in and custom errors look the same in your code.
Watching the Engine Throw Each Type
The script below triggers each engine-thrown type and prints what it catches. Run it in Node.js or paste it into a browser console.
const samples = {
'property of null': () => null.foo,
'call a non-function': () => (42)(),
'undeclared variable': () => notDeclaredAnywhere,
'negative array length': () => new Array(-1),
'toFixed out of range': () => (1).toFixed(101),
'bad JSON': () => JSON.parse('{bad'),
'bad regex': () => new RegExp('('),
'bad URI escape': () => decodeURIComponent('%'),
};
for (const [label, fn] of Object.entries(samples)) {
try {
fn();
} catch (err) {
console.log(`${label.padEnd(24)} ${err.name.padEnd(15)} ${err.message}`);
}
}The name column will be the same in every engine. The message column will not. V8 says Cannot read properties of null (reading 'foo'). Firefox says null has no properties. That difference leads to the first rule of this chapter.
SyntaxError: Parse Time Versus Run Time
SyntaxError behaves differently depending on when it happens. A syntax error in your own source file is reported while the engine parses the file, before any of its code runs. No try/catch in that file can catch it, because the try statement never runs.
try {
// If this file contained `let x = ;`, the whole file would fail to load.
// The try block below would never execute.
JSON.parse('{"a": 1,}');
} catch (err) {
console.log(err instanceof SyntaxError); // true: JSON.parse runs at run time
}You can only catch a SyntaxError when it comes from code parsed at run time: JSON.parse, the RegExp constructor, eval, new Function, or a dynamic import() of a broken module. In practice, a caught SyntaxError almost always means bad input data, not a bug in your code.
ReferenceError and the Temporal Dead Zone
A ReferenceError usually means a typo or a missing import. It also appears when code reads a let, const, or class binding before its declaration has run. The time between entering the scope and reaching the declaration is called the temporal dead zone.
function show() {
try {
console.log(value);
} catch (err) {
console.log(err.name); // 'ReferenceError'
}
const value = 1;
}
show();A ReferenceError points to a bug in your code. Catching it and carrying on hides that bug.
Throwing Built-ins in Your Own Code
TypeError and RangeError are the two built-ins worth throwing yourself. Use them for argument validation, the same way the standard library does:
function repeatText(text, times) {
if (typeof text !== 'string') {
throw new TypeError(`text must be a string, got ${typeof text}`);
}
if (!Number.isInteger(times) || times < 0) {
throw new RangeError(`times must be a non-negative integer, got ${times}`);
}
return text.repeat(times);
}
console.log(repeatText('ab', 3)); // 'ababab'
try {
repeatText('ab', -1);
} catch (err) {
console.log(err.name, err.message); // 'RangeError times must be a non-negative integer, got -1'
}The rule of thumb is that a wrong kind of value gets a TypeError and a right kind of value with a bad amount gets a RangeError. Callers who know the standard library will understand both right away.
Built-ins have a limit. They describe what was wrong with a value. They don't describe a failure in your domain, such as "user not found" or "payment declined". ReferenceError and URIError say nothing useful about your application, and SyntaxError should be reserved for parsers. When the failure belongs to your domain, you need a custom class, and the next chapter shows how to write one.
Errors from the Host Environment
Browsers and Node.js add errors beyond the language specification, and they tag them in different ways.
| Source | What you receive | How to tell them apart |
|---|---|---|
| Browser and Node.js web APIs | `DOMException`, for example when `fetch` is aborted | `err.name`, such as `'AbortError'` or `'TimeoutError'` |
| Node.js system calls | A plain `Error` with extra fields | `err.code` (`'ENOENT'`, `'ECONNRESET'`), plus `errno`, `syscall`, and `path` |
| Node.js argument validation | A built-in such as `TypeError` or `RangeError` with a `code` | `err.code`, such as `'ERR_INVALID_ARG_TYPE'` |
import { readFile } from 'node:fs/promises';
try {
await readFile('/definitely/missing.txt', 'utf8');
} catch (err) {
console.log(err instanceof Error); // true
console.log(err.constructor.name); // 'Error'
console.log(err.code); // 'ENOENT'
console.log(err.syscall); // 'open'
}Node.js uses a plain Error with a code field for system failures because there are hundreds of system error codes, and one class per code would be impractical. The last chapter of this tutorial comes back to this choice between a class and a code.
Common Mistakes
- Catching
TypeErrortoo broadly. Acatchthat swallows everyTypeErroralso hides real bugs such asundefined.foo. Keeptryblocks small, and rethrow anything you did not expect. - Matching message strings. Messages differ between engines, as the sample script showed.
- Throwing non-errors.
throw 'failed'produces no stack trace and fails everyinstanceof Errorcheck. Always throw anErroror a subclass. - Expecting
EvalError. Modern engines don't throw it. Code that checks for it is dead code. - Assuming every failure has a specific type. Many APIs, including most of Node.js, throw a plain
Errorand put the detail incode.
Exercise
Without running it, predict the name printed for each call: (a) undefined(), (b) 'abc'.repeat(-1), (c) JSON.parse(''), (d) new Array(2 ** 32).
Show answer
(a) TypeError, because undefined is not a function. (b) RangeError, because the count must be non-negative. (c) SyntaxError, because an empty string is not valid JSON. (d) RangeError, because the largest valid array length is 2 ** 32 - 1.
Exercise
A colleague writes catch (err) { if (err.message.includes('Cannot read properties')) return null; throw err; }. Explain two problems with it and suggest a better approach.
Show answer
The message text belongs to V8 and differs in Firefox and Safari, so the check fails in other engines. It also treats a programming bug (reading a property of null or undefined) as an expected condition. Instead, check for the missing value before reading the property, using optional chaining such as obj?.prop, so no error is thrown and real TypeErrors still surface.
Exercise
Write a function percent(value) that throws a TypeError when value is not a number and a RangeError when it is outside 0 to 100, and otherwise returns a string such as '42%'.
Show answer
function percent(value) { if (typeof value !== 'number' || Number.isNaN(value)) throw new TypeError(value must be a number, got ${typeof value}); if (value < 0 || value > 100) throw new RangeError(value must be between 0 and 100, got ${value}); return ${value}%; }