Sub topic 5
The Built-in Error Types
This chapter assumes you know how to create and read Error objects, how to use throw, and how to wrap code in try/catch. It also assumes you can run small scripts in Node.js or a browser console. JavaScript has a small set of error constructors built in. The engine uses them to report what kind of failure happened, and you can use them in your own code. Knowing what each one means makes stack traces quicker to read and lets you throw errors that other developers recognize.
The Error Family
Every built-in error type is a subclass of Error. Each one inherits message and stack from Error and sets its own name on its prototype. So a TypeError is also an Error, and err.name tells you which kind it is.
The table below summarizes when you will see each type.
| Type | Meaning | Typical trigger |
|---|---|---|
| `TypeError` | A value is not the kind the operation needs | Reading a property of `null`, calling a non-function, assigning to a `const` |
| `RangeError` | A number is outside the allowed range | `new Array(-1)`, `toFixed(101)`, runaway recursion |
| `SyntaxError` | Text could not be parsed as code or data | `JSON.parse('{bad')`, `new Function('return (')` |
| `ReferenceError` | A name cannot be resolved | Using an undeclared variable, reading a `let` before its declaration |
| `URIError` | A URI function got malformed input | `decodeURIComponent('%')` |
| `EvalError` | Historic `eval` misuse | Not thrown by modern engines |
| `AggregateError` | Several errors reported together | `Promise.any` when every promise rejects |
The script below triggers five of these in a row and prints the name and message of each one.
const samples = [
() => null.length,
() => undefinedVariable,
() => JSON.parse('{bad'),
() => new Array(-1),
() => decodeURIComponent('%'),
];
for (const run of samples) {
try {
run();
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
}In Node.js the output looks like this:
TypeError: Cannot read properties of null (reading 'length')
ReferenceError: undefinedVariable is not defined
SyntaxError: Expected property name or '}' in JSON at position 1 (line 1 column 2)
RangeError: Invalid array length
URIError: URI malformedTypeError
TypeError is the error you will see most often. It means an operation received a value of the wrong kind. These are the common causes:
- Reading or writing a property on
nullorundefined. - Calling something that is not a function, for example
config.load()whenloadis undefined. - Assigning to a
constbinding. - Writing to a frozen object or a read-only property in strict mode.
- Using
newon something that is not a constructor, such as an arrow function.
'use strict';
const attempts = {
nullProperty: () => { const user = null; return user.name; },
notAFunction: () => { const settings = {}; settings.load(); },
constAssign: () => { const limit = 1; limit = 2; },
frozenWrite: () => { const point = Object.freeze({ x: 1 }); point.x = 2; },
arrowWithNew: () => { const make = () => {}; return new make(); },
};
for (const [label, fn] of Object.entries(attempts)) {
try {
fn();
} catch (err) {
console.log(label, '->', err.name);
}
}
// Every line prints TypeErrorIn sloppy mode (non-strict code), writing to a frozen object fails silently and throws nothing. This is one reason modules and classes run in strict mode automatically.
RangeError
RangeError means a value has the right type but is out of bounds. Built-in methods throw it when an argument has to fall inside a fixed range.
const checks = [
() => new Array(-1),
() => (3.14159).toFixed(101),
() => 'ab'.repeat(-1),
() => (255).toString(1),
() => new Intl.NumberFormat('en', { maximumFractionDigits: 200 }),
];
for (const fn of checks) {
try {
fn();
} catch (err) {
console.log(err.name, '-', err.message);
}
}Stack overflow is engine-specific
Recursion without a base case runs out of stack. V8 (Chrome and Node.js) and JavaScriptCore (Safari) report this as a RangeError: Maximum call stack size exceeded. Firefox throws a non-standard InternalError: too much recursion. You can catch a stack overflow, but the catch block itself runs with very little stack left. Logging and rethrowing is about all that is safe to do there. Never use it as a way to control program flow.
function forever(n) {
return forever(n + 1);
}
try {
forever(0);
} catch (err) {
console.log(err.name); // RangeError in Node.js and Chrome
}SyntaxError
SyntaxError means some text could not be parsed. When this happens matters a lot.
- Parse-time errors in your own script happen before any of the script runs. A
try/catchin the same file cannot catch them, because that file never starts executing. - Runtime parsing happens when your code hands text to a parser while it runs:
JSON.parse,new Function,eval,new RegExp, or a dynamicimport()of a broken module. You can catch these errors.
const inputs = ['{"ok": true}', "{'single': 'quotes'}", ''];
for (const text of inputs) {
try {
console.log(JSON.parse(text));
} catch (err) {
console.log(err instanceof SyntaxError, err.message);
}
}
try {
new RegExp('(unclosed');
} catch (err) {
console.log(err.name); // SyntaxError
}An empty string is invalid JSON. If a server can send an empty response body, check for it before you call JSON.parse, or handle the SyntaxError.
ReferenceError
ReferenceError means a name could not be resolved at all. Usually the cause is a typo or a missing import. The less obvious cause is the temporal dead zone: the stretch of code before a let, const, or class declaration in the same scope. Accessing the binding there throws, even though the declaration exists further down.
try {
console.log(count);
let count = 1;
} catch (err) {
console.log(err.name, '-', err.message);
// ReferenceError - Cannot access 'count' before initialization
}
console.log(typeof notDeclaredAnywhere); // 'undefined', no errortypeof on a name that was never declared returns 'undefined' and does not throw. Inside the temporal dead zone, typeof still throws a ReferenceError.
URIError and EvalError
URIError comes from decodeURI, decodeURIComponent, encodeURI, and encodeURIComponent when the input is malformed. You will usually hit it while decoding user-supplied query strings or path segments:
function safeDecode(segment) {
try {
return decodeURIComponent(segment);
} catch (err) {
if (err instanceof URIError) return segment;
throw err;
}
}
console.log(safeDecode('caf%C3%A9')); // café
console.log(safeDecode('100%')); // 100%Encoding can also throw. encodeURIComponent('\uD800') throws a URIError because a lone surrogate cannot be encoded as UTF-8.
EvalError remains in the language only for backward compatibility. Current engines do not throw it. Do not use it in new code.
AggregateError
AggregateError carries several errors at once in its errors array. Promise.any rejects with one when every input promise rejects. You can also construct one yourself, for example to report every failed validation together.
Promise.any([
Promise.reject(new Error('primary down')),
Promise.reject(new TypeError('backup misconfigured')),
]).catch((err) => {
console.log(err.name); // AggregateError
console.log(err.errors.map((e) => e.name)); // [ 'Error', 'TypeError' ]
});
const failures = [new RangeError('age too low'), new TypeError('name missing')];
const combined = new AggregateError(failures, 'Form has 2 problems');
console.log(combined.message, combined.errors.length); // Form has 2 problems 2Note that the constructor takes the errors first and the message second, which is the opposite of what many people expect.
Throwing Built-in Types Yourself
You are not limited to plain Error. When the meaning fits, throw a built-in type. It tells callers what went wrong without making them read the message, and other developers already know what it means.
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);
}
for (const args of [['ab', 2], [42, 2], ['ab', -1]]) {
try {
console.log(repeatText(...args));
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
}A common convention: use TypeError for an argument of the wrong kind and RangeError for a value of the right kind that is out of bounds. Avoid throwing SyntaxError or ReferenceError from application code. Readers treat those as problems with the code itself, not with the data. For failures specific to your domain, such as a failed validation or a missing record, define your own classes. The next chapter covers that.
Errors That Are Not in This Family
Some errors you will catch are not instances of these constructors, or they carry extra information:
DOMException: browser APIs andfetchreport many failures with it. An aborted request rejects with aDOMExceptionwhosenameis'AbortError'. Checkerr.namefor these.- Node.js system errors: these are ordinary
Errorobjects with extra properties such ascode('ENOENT','ECONNREFUSED') andsyscall. Branch onerr.code, not on the message. - Errors from another realm: an error created in an iframe or a Node.js
vmcontext has a differentTypeErrorconstructor, soinstanceof TypeErrorreturnsfalsein your realm. In that caseerr.name === 'TypeError'still works. - Non-errors: JavaScript lets code throw any value, including strings or plain objects. Those have no
nameorstackat all.
Exercise
What does each line throw? (a) undefined() (b) new Array(2 ** 32) (c) JSON.parse('[1, 2,]') (d) decodeURIComponent('%E0%A4%A')
Show answer
(a) TypeError, because undefined is not a function. (b) RangeError, because array length must be below 2^32. (c) SyntaxError, because JSON does not allow trailing commas. (d) URIError, because the percent-encoded sequence is incomplete.
Exercise
A function setVolume(level) accepts integers from 0 to 100. Which built-in type should it throw for setVolume('loud'), and which for setVolume(150)? Write the two guard clauses.
Show answer
Throw TypeError for 'loud' (wrong kind of value) and RangeError for 150 (right kind, out of bounds): if (!Number.isInteger(level)) throw new TypeError('level must be an integer'); then if (level < 0 || level > 100) throw new RangeError('level must be between 0 and 100');
Exercise
Why can't a try/catch at the top of app.js catch a SyntaxError caused by a missing brace later in app.js, when it can catch the SyntaxError from JSON.parse?
Show answer
A missing brace is a parse-time error. The engine rejects the whole script before running any of it, so the try statement never executes. JSON.parse runs while the program is executing and parses text at that point, so the error is thrown inside the active try block.