Sub topic 2
The Built-in Error Types
This chapter assumes you know throw and try/catch and have read the previous chapter on the name, message, and stack properties. In this chapter you will see which error types JavaScript already provides, what triggers each one, and when your own code should throw them.
The standard constructors
ECMAScript defines a small set of error constructors. Each one is a subclass of Error, so every instance has name, message, and stack. Each instance is also instanceof Error.
| Constructor | Typical trigger |
|---|---|
| `TypeError` | A value has the wrong type for the operation, for example calling a method on `null` or calling something that is not a function |
| `RangeError` | A numeric value is outside its allowed range, for example `new Array(-1)` or `(1).toFixed(200)` |
| `SyntaxError` | Text fails to parse, as with `JSON.parse`, `eval`, or `new Function` |
| `ReferenceError` | Code reads an undeclared variable, or reads a `let`/`const` before its declaration runs |
| `URIError` | `decodeURIComponent` or `encodeURI` receives malformed input |
| `EvalError` | Kept for compatibility. The engine no longer throws it |
| `AggregateError` | Several errors are grouped into one. A later chapter covers it |
Seeing them in action
Run this in Node.js or a browser console. It triggers five of the types and prints what each caught error reports.
const cases = [
() => null.toUpperCase(),
() => new Array(-1),
() => JSON.parse('{bad'),
() => notDeclaredAnywhere,
() => decodeURIComponent('%'),
];
for (const fn of cases) {
try {
fn();
} catch (err) {
console.log(err.name.padEnd(15), err instanceof Error, err.message);
}
}
// TypeError true Cannot read properties of null (reading 'toUpperCase')
// RangeError true Invalid array length
// SyntaxError true Expected property name or '}' in JSON at position 1 ...
// ReferenceError true notDeclaredAnywhere is not defined
// URIError true URI malformedThe name values are stable across engines. The message text is not. V8, SpiderMonkey, and JavaScriptCore word their messages differently, and the wording changes between versions.
Throwing built-in types yourself
You don't need a custom class for every failure. If a built-in type describes the problem exactly, throw that type. Callers and tools already know what it means.
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 between 0 and 100, got ${level}`);
}
return level;
}
try {
setVolume(150);
} catch (err) {
console.log(err.name, err.message); // RangeError level must be between 0 and 100, got 150
}A useful rule: use TypeError for argument validation of type or shape, and RangeError for values of the right type that fall outside the allowed bounds. Don't throw SyntaxError or ReferenceError for application problems. Developers read those as signs of broken code, not bad input.
Common mistakes
- Expecting to catch your own syntax errors. A
SyntaxErrorin your source file is reported when the script is parsed, before anytryblock runs. You can only catchSyntaxErrorfrom runtime parsing such asJSON.parse. - Treating host errors as built-ins.
DOMExceptionin browsers and the system errors in Node.js (which have codes likeerr.code === 'ENOENT') come from the host environment, not ECMAScript. Node's system errors are plainErrorinstances, so you tell them apart bycode, not by class. - Throwing plain
Errorfor everything.throw new Error('bad type')hides information thatTypeErrorwould give callers for free.
Exercise
A function parseAge(input) receives a string, converts it with Number(input), and must reject non-numeric strings and ages below 0 or above 150. Which built-in error type should it throw for "abc", and which for "200"? Explain why.
Show answer
For "abc", throw TypeError, because Number("abc") is NaN and the input does not describe a number at all, so its shape is invalid. For "200", throw RangeError, because the value is a valid number that falls outside the allowed bounds. Some teams use RangeError for NaN too. The important part is to apply one rule consistently and never to rely on message text.
Exercise
Why does wrapping a file that contains const x = ; in try/catch not catch the resulting SyntaxError?
Show answer
The engine parses the whole script before running any of it. The SyntaxError is raised during parsing, so no try block has started executing. Only code parsed at runtime, such as JSON.parse, eval, or new Function, produces a SyntaxError that you can catch.