Sub topic 2
Throwing Errors on Purpose
This chapter assumes you can write functions and classes, run a script with Node.js or in the browser console, and read an Error's name, message, and stack, which the previous chapter covered. Catching errors gets a full treatment in the next chapter. Here, try/catch shows up only in a few small examples so you can see what was thrown.
Most errors you meet early on come from the runtime. You call a method on undefined, or you pass bad text to JSON.parse. Your own code can raise errors too. When a function receives input it cannot work with, or it cannot keep its promise to the caller, it can stop and report the problem with the throw statement.
The throw statement
throw takes one expression. It evaluates the expression and stops running the current function at once. Nothing after the throw in that block runs.
function parseQuantity(input) {
const n = Number(input);
if (!Number.isInteger(n) || n <= 0) {
throw new Error(`Invalid quantity: ${JSON.stringify(input)}`);
}
return n;
}
console.log(parseQuantity('3')); // 3
console.log(parseQuantity('abc')); // throws
console.log('never printed');Run it with Node.js and you get the first result, followed by a report like this:
3
/home/me/order.js:4
throw new Error(`Invalid quantity: ${JSON.stringify(input)}`);
^
Error: Invalid quantity: "abc"
at parseQuantity (/home/me/order.js:4:11)
at Object.<anonymous> (/home/me/order.js:10:13)
...The third console.log never runs. Nothing caught the error, so Node.js printed it and ended the process with a non-zero exit code. A browser prints a similar "Uncaught Error" message in the console and abandons the current task, but the page keeps running.
new Error(message) and Error(message) behave the same. Calling Error without new still returns a new Error object. Most codebases write new anyway, for consistency with other classes.
How a throw travels up the call stack
A thrown value does not just leave the function that threw it. The engine leaves that function, then checks whether the caller was inside a try block. If the caller was not, the engine leaves the caller as well, and keeps going up the call stack. This process is called unwinding. It stops at the first enclosing try with a catch. If there is none, the error is uncaught.
function parseQuantity(input) {
const n = Number(input);
if (!Number.isInteger(n) || n <= 0) {
throw new Error(`Invalid quantity: ${JSON.stringify(input)}`);
}
return n;
}
function buildLine(item, qtyText) {
const qty = parseQuantity(qtyText);
console.log('buildLine finished'); // skipped when parseQuantity throws
return { item, qty };
}
function buildOrder(lines) {
const result = lines.map(([item, qty]) => buildLine(item, qty));
console.log('buildOrder finished'); // skipped as well
return result;
}
try {
buildOrder([['apple', '2'], ['pear', '-1']]);
} catch (err) {
console.log('Caught at the top:', err.message);
}Output:
buildLine finished
Caught at the top: Invalid quantity: "-1"The first line built fine. On the second line, parseQuantity threw. The rest of buildLine, the rest of the map callback, map itself, and the rest of buildOrder were all skipped. Neither buildLine nor buildOrder needed code to pass the failure along. Unwinding did it for them, which is the main advantage of throwing over returning error codes.
You can throw anything, but throw Error objects
The language lets you throw any value at all:
function readDisk() {
throw 'disk full';
}
try {
readDisk();
} catch (e) {
console.log(typeof e); // 'string'
console.log(e.stack); // undefined
console.log(e.message); // undefined
}It is legal, but it causes problems:
- A string, number, or plain object has no
stack, so nothing tells you where the failure happened. - Code that reads
err.messagegetsundefined. err instanceof Erroris false, so the type checks covered later in this tutorial fail.- Logging tools and test runners expect Error objects and show raw values badly.
Linters flag this pattern. ESLint's no-throw-literal rule and TypeScript-ESLint's only-throw-error rule both report it. Throw Error or a subclass of it. If you need extra data, attach it to an Error object instead of throwing a plain object:
const err = new Error('Payment declined');
err.code = 'CARD_DECLINED';
throw err;Custom error classes, covered later, do the same thing more cleanly.
The stack is recorded when the Error is created
The stack property is filled in when the Error object is constructed, not when it is thrown. Usually the two happen on the same line, so the difference does not matter. It does matter if you build an error ahead of time and reuse it:
const NOT_FOUND = new Error('Record not found'); // stack recorded here
function findUser(id) {
if (id !== 1) throw NOT_FOUND;
return { id, name: 'Ada' };
}
try {
findUser(42);
} catch (err) {
console.log(err.stack);
}The printed stack points at line 1, the module top level, and never mentions findUser. Every throw shares the same object, so code that adds properties to it changes the error for every later throw too. Create a new Error at the point of failure each time.
A related case: if a helper function builds the error, the helper appears as the top frame of the stack. In V8 (Node.js and Chrome) you can hide it with the non-standard Error.captureStackTrace(err, helperFn). Most code does not need this.
throw is a statement, not an expression
throw is a statement. You cannot use it where JavaScript expects a value:
// SyntaxError: these do not parse
const port = env.PORT ?? throw new Error('PORT is not set');
const fail = () => throw new Error('nope');A proposal to allow throw expressions exists, but it has not become part of the language. You have two standard workarounds. You can give the arrow function a block body, () => { throw new Error('nope'); }. Or you can write a small helper function, since a function call is an expression:
function fail(message) {
throw new Error(message);
}
function getPort(env) {
const port = env.PORT ?? fail('PORT is not set');
return Number(port);
}
console.log(getPort({ PORT: '8080' })); // 8080
console.log(getPort({})); // throws Error: PORT is not setThe newline gotcha
Automatic semicolon insertion treats a line break right after throw as an error:
// SyntaxError: Illegal newline after throw
throw
new Error('Something broke');Keep the start of the expression on the same line as throw. Long messages can wrap after that point.
Throwing inside constructors and setters
A constructor that throws prevents the object from being created, and the new expression produces no value. This lets you refuse to build an object in an invalid state:
class Temperature {
constructor(celsius) {
if (typeof celsius !== 'number' || Number.isNaN(celsius)) {
throw new TypeError('celsius must be a number');
}
if (celsius < -273.15) {
throw new RangeError('Temperature below absolute zero');
}
this.celsius = celsius;
}
}
const t = new Temperature(21);
console.log(t.celsius); // 21
new Temperature(-300); // throws RangeErrorThe built-in TypeError and RangeError constructors are used here the same way as Error. A later chapter explains when to pick each built-in type.
When to throw and when to return
Throwing is for situations where a function cannot do what its name and signature promise. A missing value that callers routinely expect should be part of the return value, so callers don't have to wrap every call in try.
| Situation | Usual choice | Example |
|---|---|---|
| Caller broke the contract (wrong type, impossible value) | Throw | `new Temperature('hot')` |
| Operation failed and the function has nothing valid to return | Throw | Config file is missing required keys |
| "Not found" is a normal, expected outcome | Return `undefined` or `null` | `Array.prototype.find` |
| Validating user input where many failures are expected | Return a result, such as `{ ok, errors }` | Form validation listing every bad field |
| Internal invariant broken, which means a bug | Throw | A state machine reaches an unknown state |
Throw at the point where the problem is detected, and check inputs early with guard clauses at the top of the function. The error message should say what was wrong and include the offending value, as Invalid quantity: "-1" does. A message like Invalid input forces whoever reads the log to reproduce the bug before they can understand it.
Exercises
Exercise
Write a function divide(a, b) that returns a / b, throws a TypeError if either argument is not a number, and throws a RangeError if b is 0. Each message should include the offending value(s).
Show answer
function divide(a, b) { if (typeof a !== 'number' || typeof b !== 'number') { throw new TypeError(divide expects numbers, got ${typeof a} and ${typeof b}); } if (b === 0) { throw new RangeError(Cannot divide ${a} by zero); } return a / b; } — divide(6, 3) returns 2, divide(1, 0) throws RangeError, and divide('6', 3) throws TypeError.
Exercise
A teammate writes const ERR = new Error('timeout'); at the top of a module and later uses throw ERR; in three different functions. What two problems does this cause?
Show answer
First, the stack trace was recorded when ERR was created at module load, so it points at the top of the module and not at the function that failed. Second, all three throws share one object, so any property a handler sets on it (such as err.retried = true) leaks into every later throw. Create a new Error at each throw site.
Exercise
Why does const name = user.name || throw new Error('no name'); fail, and how can you write it with standard JavaScript?
Show answer
throw is a statement, and the right side of || must be an expression, so the line is a SyntaxError. Define a helper such as function fail(msg) { throw new Error(msg); } and write const name = user.name || fail('no name');. You can also use an if statement before the assignment.