Sub topic 2
Throwing Errors on Purpose
This chapter assumes you can write JavaScript functions and use control flow, and that you know how to run a script in Node.js or the browser console. It builds on the previous chapter's Error objects and their name, message, and stack properties.
The throw statement
So far you have seen errors that JavaScript raises by itself, such as calling undefined as a function. Your own code can raise an error too, with the throw statement:
throw new Error('Something went wrong');When throw runs, the current function stops at that line. Nothing after it runs. JavaScript then hands the error to the function that called this one. If that caller does not handle the error, it stops too, and so on up the call stack. When no code handles the error, the runtime reports it as uncaught. Node.js prints the stack and exits. The browser logs it to the console.
Throwing to enforce your function's contract
Throw when a function gets input it cannot sensibly work with. Without the throw, the function would return a wrong result and the caller would never know. A common pattern is the guard clause, a check at the top of the function that throws before any real work starts:
function computeTotal(price, quantity) {
if (typeof price !== 'number' || Number.isNaN(price)) {
throw new TypeError(`price must be a number, got ${typeof price}`);
}
if (!Number.isInteger(quantity) || quantity < 1) {
throw new RangeError(`quantity must be a positive integer, got ${quantity}`);
}
return price * quantity;
}
console.log(computeTotal(9.5, 2)); // 19
console.log(computeTotal(9.5, 0)); // throws RangeError; this line never logs
console.log('done'); // never runsRun this and you get 19, then an uncaught RangeError with a stack trace that points at the throw line. done never prints. Failing early like this means the error message describes the real problem. Otherwise you might get a confusing NaN three functions later.
The example uses TypeError and RangeError instead of plain Error. A later chapter covers the built-in types. For now, notice that choosing a specific type tells the reader what kind of problem occurred.
Throw Error objects, not other values
JavaScript lets you throw any value, including a string, a number, or a plain object:
function badThrow() {
throw 'quantity is invalid'; // legal, but a bad idea
}Avoid this. A string has no stack property, so you cannot see where it came from. Code that handles errors usually expects err.message and err.name, and those are undefined on a string. Tools such as loggers and error trackers also assume Error objects. Always throw new Error(...) or a subclass of it.
Writing useful messages
The message is often the only thing a developer sees in a log. Make it specific:
| Weak message | Better message |
|---|---|
| `Invalid input` | `quantity must be a positive integer, got -3` |
| `Error loading` | `Config file not found: ./settings.json` |
| `Bad value` | `price must be a number, got string` |
Include what was expected and what was received. Leave out secrets such as passwords or tokens, because messages end up in logs.
Common mistakes
- Returning
nullor-1to signal failure when the caller is likely to ignore it. Throwing forces the problem into view. - Using
throwfor normal, expected outcomes, such as "no search results". Return an empty array instead. - Forgetting
new.throw Error('x')happens to work, butnew Error('x')states the intent clearly and works the same way for classes you define yourself.
The next chapter shows how to stop a thrown error from going all the way up the stack by catching it with try and catch.
Exercise
Write a function divide(a, b) that throws a RangeError with a useful message when b is 0, and otherwise returns a / b. What happens to code that comes after a call to divide(1, 0) in the same function, if nothing handles the error?
Show answer
function divide(a, b) { if (b === 0) { throw new RangeError(cannot divide ${a} by zero); } return a / b; } — After divide(1, 0) throws, the rest of the calling function does not run. The error moves up the call stack, and if nothing handles it, it is reported as an uncaught RangeError with a stack trace.
Exercise
Why is throw new Error('not found') better than throw 'not found'?
Show answer
An Error object records a stack trace that shows where the error was thrown, and it has name and message properties that handlers, loggers, and error trackers rely on. A thrown string has none of these.