Programs that fail clearly
Every real program meets bad input, missing files, networks that drop, and its own bugs. The question is not whether it will fail but how: silently, producing wrong answers that someone notices weeks later, or loudly and immediately, with a message that says what went wrong and where. JavaScript's history leans towards silence (remember "5" - 2 and NaN quietly spreading through a calculation), so the habits in this lesson matter more than in stricter languages.
There are two halves. Errors are how a program reports, at run time, that something cannot be done. Tests are how you find out, before your users do, that something is being done wrong. Both have good built-in support: the language's Error classes and try/catch, and, since Node 20, a test runner and assertion library that ship with Node itself, so you can test without installing anything.
Errors the engine throws, and try/catch/finally
When an operation is impossible, the engine throws an exception: normal execution stops, and the engine unwinds the call stack looking for a catch block. If none is found, the program ends with the error message and a stack trace (in a browser, the error is logged to the console and that one task is abandoned).
// Errors the engine throws for you.
const attempts = [
() => null.length, // reading a property of null
() => undeclaredVariable + 1, // a name that doesn't exist
() => (42)(), // calling something that isn't a function
() => new Array(-1), // an impossible length
() => JSON.parse("{ name: 'Ada' }"), // invalid JSON (keys need double quotes)
() => 10n + 1, // mixing BigInt and number
];
for (const attempt of attempts) {
try {
attempt();
} catch (err) {
console.log(`${err.name}: ${err.message}`);
}
}
// try / catch / finally: finally runs whatever happens.
function divide(a, b) {
try {
if (b === 0) throw new RangeError("cannot divide by zero");
return a / b;
} catch (err) {
console.log("caught:", err.message);
return NaN;
} finally {
console.log(`finally: divide(${a}, ${b}) is done`);
}
}
console.log(divide(10, 4));
console.log(divide(1, 0));
// An Error object carries a name, a message and a stack trace.
const err = new TypeError("expected a string");
console.log(err instanceof TypeError, err instanceof Error, err.name);
console.log(err.stack.split("\n")[0]);TypeError: Cannot read properties of null (reading 'length')
ReferenceError: undeclaredVariable is not defined
TypeError: 42 is not a function
RangeError: Invalid array length
SyntaxError: Expected property name or '}' in JSON at position 2 (line 1 column 3)
TypeError: Cannot mix BigInt and other types, use explicit conversions
finally: divide(10, 4) is done
2.5
caught: cannot divide by zero
finally: divide(1, 0) is done
NaN
true true TypeError
TypeError: expected a stringThe built-in error types tell you what kind of mistake happened:
| Type | Typical cause |
|---|---|
TypeError | using a value in a way its type doesn't allow: a property of null or undefined, calling a non-function, writing to a frozen object |
ReferenceError | a name that doesn't exist, or a let/const used before its declaration |
RangeError | a number outside the allowed range: array length, toFixed(200), recursion too deep |
SyntaxError | code that doesn't parse (when the module loads), or text that isn't valid JSON (JSON.parse) |
The message wording comes from the engine; Firefox and Safari phrase the same errors differently, so never write code that inspects error messages from the engine. Check err.name or use instanceof.
finally runs after the try (and the catch, if there was one) whatever happened: normal completion, a return, or an exception. Notice that divide(10, 4) printed its finally line before 2.5: the return a / b computed the value, then finally ran, then the value was handed back. That makes finally the place for cleanup that must always happen, such as closing a file, releasing a lock, or hiding a loading spinner. If you don't need the error object, ES2019 lets you write just catch { ... } without a parameter.
Throwing your own errors
You can throw any value, but always throw an Error (or a subclass). Only Error objects capture a stack trace, the list of function calls that led to the problem, which is what makes an error in a log debuggable. throw "something broke" gives the catcher a bare string with no stack and no name.
// Custom errors, causes, and catching only what you can handle.
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
class ConfigError extends Error {
constructor(message, options) {
super(message, options); // options may hold { cause }
this.name = "ConfigError";
}
}
function parsePort(value) {
const port = Number(value);
if (!Number.isInteger(port) || port < 1 || port > 65535) {
throw new ValidationError("port", `port must be an integer from 1 to 65535, got "${value}"`);
}
return port;
}
function loadConfig(text) {
let raw;
try {
raw = JSON.parse(text);
} catch (err) {
throw new ConfigError("config file is not valid JSON", { cause: err });
}
return { host: raw.host ?? "localhost", port: parsePort(raw.port ?? 8080) };
}
const inputs = [
'{ "host": "example.org", "port": 443 }',
'{ "port": "eighty" }',
"{ port: 80 }",
"{}",
];
for (const text of inputs) {
try {
console.log("loaded", loadConfig(text));
} catch (err) {
if (err instanceof ValidationError) {
console.log(`invalid ${err.field}: ${err.message}`);
} else if (err instanceof ConfigError) {
console.log(`${err.name}: ${err.message}`);
console.log(` caused by ${err.cause.name}`);
} else {
throw err; // not ours: let it propagate
}
}
}loaded { host: 'example.org', port: 443 }
invalid port: port must be an integer from 1 to 65535, got "eighty"
ConfigError: config file is not valid JSON
caused by SyntaxError
loaded { host: 'localhost', port: 8080 }Four professional habits are packed into this program.
Subclass Error for errors your callers may want to handle differently, and set name (it is not set automatically: a subclass would otherwise still say "Error"). Extra fields, like field here, let the catcher react precisely: a web form can highlight the right input.
Wrap low-level errors with a cause. The caller of loadConfig should not have to know that JSON parsing is involved; it gets a ConfigError that speaks its language. But the original SyntaxError is not thrown away: the cause option (ECMAScript 2022) attaches it, and Node prints the whole chain when an error goes uncaught. Losing the original error is one of the most common reasons a production bug takes days rather than minutes to diagnose.
Catch only what you can handle, and rethrow the rest. The else { throw err; } branch matters. A catch block that swallows every error, perhaps with a vague console.log("something went wrong"), turns a typo in your own code into a mystery. Catch at the level that can do something useful (show a message, retry, use a default), and let everything else propagate to a top-level handler that logs it.
Validate at the boundary. parsePort checks data at the moment it enters the program, from a file, and fails with a message that names the bad value. Code deeper inside can then trust that port is a valid number. The same applies to form input, query strings, environment variables and API responses: convert and check once, at the edge.
Note
Throw or return? Exceptions are for situations the caller cannot reasonably be expected to check for in advance, or that should stop the operation: invalid configuration, a broken invariant, a failed network request. For expected outcomes, return a value: find returns undefined when nothing matches, and a function that validates a form might return a list of problems rather than throwing on the first one. Some teams use explicit result objects, such as { ok: true, value } and { ok: false, error }, for operations that fail routinely.
Testing with node:test
A unit test calls a piece of code with known inputs and asserts that the result is what it should be. A suite of such tests, run after every change, tells you within seconds whether you broke something. Node ships a test runner (node:test, stable since Node 20) and an assertion library (node:assert). Here is a function together with its tests, in one file for the sake of the lesson; in a real project, parseDuration would live in its own module and the test file would import it.
// duration.test.mjs: a function and its tests, using Node's built-in test runner.
import { describe, test } from "node:test";
import assert from "node:assert/strict";
// The code under test. In a real project it would live in its own module.
function parseDuration(text) {
if (typeof text !== "string") {
throw new TypeError("duration must be a string");
}
const match = /^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/.exec(text.trim());
if (match === null || text.trim() === "") {
throw new RangeError(`not a duration: "${text}"`);
}
const [, hours = "0", minutes = "0", seconds = "0"] = match;
return Number(hours) * 3600 + Number(minutes) * 60 + Number(seconds);
}
describe("parseDuration", () => {
test("reads hours, minutes and seconds", () => {
assert.equal(parseDuration("1h30m"), 5400);
assert.equal(parseDuration("45s"), 45);
assert.equal(parseDuration("1h1m1s"), 3661);
});
test("ignores surrounding spaces", () => {
assert.equal(parseDuration(" 2h "), 7200);
});
test("works on many inputs at once", () => {
const inputs = ["1m", "10m", "1h"];
assert.deepEqual(inputs.map(parseDuration), [60, 600, 3600]);
});
test("rejects text that is not a duration", () => {
assert.throws(() => parseDuration(""), RangeError);
assert.throws(() => parseDuration("90 minutes"), /not a duration/);
});
test("rejects values that are not strings", () => {
assert.throws(() => parseDuration(90), { name: "TypeError", message: "duration must be a string" });
});
});Save it as duration.test.mjs and run node --test in its folder. Node finds files whose names match its test patterns (such as *.test.mjs), runs them, and in a terminal prints:
▶ parseDuration
✔ reads hours, minutes and seconds (0.499259ms)
✔ ignores surrounding spaces (0.083622ms)
✔ works on many inputs at once (0.53879ms)
✔ rejects text that is not a duration (0.305009ms)
✔ rejects values that are not strings (0.14926ms)
✔ parseDuration (2.737219ms)
ℹ tests 5
ℹ suites 1
ℹ pass 5
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 39.302893The times will differ on your machine. (When the output is not a terminal, as on a build server, Node switches to the machine-readable TAP format, and --test-reporter=spec switches it back.) The exit status is 0 when every test passes and 1 when any fails, which is what continuous-integration services check.
The assertions you will use most, from node:assert/strict (always import the strict flavour, which compares with ===-like rules):
| Assertion | Passes when |
|---|---|
assert.equal(actual, expected) | Object.is(actual, expected): same primitive, or same object |
assert.deepEqual(actual, expected) | the two have the same structure and contents, recursively |
assert.throws(fn, expected) | calling fn throws an error matching a class, a regular expression for the message, or an object of expected properties |
assert.ok(value) | value is truthy |
await assert.rejects(promise, expected) | the promise rejects as described (lesson eight) |
Reading a failure
Suppose someone "simplifies" the function and types Number(minutes) * 100. Running the tests again prints (abridged, with the stack traces removed):
▶ parseDuration
✖ reads hours, minutes and seconds (0.891794ms)
✔ ignores surrounding spaces (0.125481ms)
✖ works on many inputs at once (0.719904ms)
✔ rejects text that is not a duration (0.430009ms)
✔ rejects values that are not strings (0.162713ms)
✖ parseDuration (3.4746ms)
ℹ tests 5
ℹ suites 1
ℹ pass 3
ℹ fail 2
✖ failing tests:
test at duration.test.mjs:19:3
✖ reads hours, minutes and seconds (0.891794ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
6600 !== 5400Read it from the top: which tests failed (the two that involve minutes; the others still pass, which already narrows the search), then the assertion with the actual value first and the expected value second, then the file and line. For deepEqual failures Node prints a diff, marking the actual values with + and the expected ones with -.
What to test
Test behaviour, not implementation: what goes in and what comes out, so you can rewrite the inside without rewriting the tests. Cover the ordinary case, the edges (empty input, zero, the largest allowed value, non-ASCII text), and every error path. When you fix a bug, first write a test that reproduces it, watch it fail, then fix the code and watch it pass; the test keeps the bug from coming back. Many teams use a third-party framework such as Vitest or Jest instead of node:test, mainly for watch mode, browser-like environments and integration with their bundler. The ideas, and even most of the function names (describe, test, expect-style or assert-style checks), carry over directly.
Debugging: from a stack trace to the bug
Tests tell you that something is wrong; finding why is debugging, and JavaScript developers have good tools for it.
Read the stack trace from the top. When an error goes uncaught, Node prints the error's name and message, then the stack: one line per function call that was in progress, innermost first, each with a file, line and column. The first line that points into your code (rather than node:internal or a package in node_modules) is usually where to look. If the error has a cause, Node prints it too, indented under [cause], so wrapping errors costs you nothing when debugging. Browsers show the same information in the console, with clickable links to the source.
Log with intent. console.log is the oldest debugger and still a good one, but label what you print (console.log("cart before discount", cart) rather than a bare value), and know its siblings: console.error writes to standard error, which keeps diagnostics out of a program's real output; console.table(rows) prints an array of objects as a table; console.dir(obj, { depth: null }) shows deeply nested objects in full in Node. Remove debugging logs before committing; a linter rule (no-console) can remind you.
Use a real debugger. Put the statement debugger; in your code, or click a line number in the browser's Sources panel, and execution pauses there with every variable in scope visible, so you can step through the code one line at a time and watch values change. For Node, run node --inspect-brk main.mjs and open chrome://inspect in a Chromium-based browser, or simply press F5 in Visual Studio Code, which has a Node debugger built in. Ten minutes stepping through a confusing function often beats an hour of adding console.log lines.
Make the bug small. When a failure is hard to understand, cut the program down: remove code until the bug disappears, then put back the last piece. What remains is usually small enough to understand, and it makes a ready-made test case.
Common misconceptions
Misconception
"A try/catch around everything makes code robust." It makes failures invisible. Robust code fails early, with a clear error, at a place that can be found; it catches errors only where it can do something about them, and lets the rest reach a top-level handler that logs them.
Misconception
"try/catch catches errors in callbacks I start inside it." It catches errors thrown while the try block runs. A callback passed to setTimeout runs later, after the try has finished, so its errors escape. Promises and async/await (next lesson) are how JavaScript brings errors from asynchronous work back to a catch.
Misconception
"assert.equal([1, 2], [1, 2]) passes." It fails: two separately created arrays are different objects. Use assert.deepEqual to compare contents.
Misconception
"Tests prove the code is correct." They show it is correct for the cases you tested. That is enormously valuable, but the cases you didn't think of are exactly where bugs hide, which is why testing edge cases, and adding a test for every bug found, matters so much.
Exercises
For each program, trace the order in which the blocks run before you predict the output.
1. Errors and testing
Warm-upComputationalWhat does this program print? Write the three lines in order, separated by spaces.
function f() {
try {
console.log("try");
return "returned";
} finally {
console.log("finally");
}
}
console.log(f());
2. Errors and testing
CoreComputationalWhat does this print?
try {
try {
null.x;
} catch (e) {
throw new Error("wrapped", { cause: e });
}
} catch (e) {
console.log(e.message, e.cause.name);
}
3. Errors and testing
StretchComputationalWhat number does this print?
function g() {
try {
return 1;
} finally {
return 2;
}
}
console.log(g());
4. Errors and testing
CoreComputationalWhat does this print?
class AppError extends Error {}
const e = new AppError("boom");
console.log(e.name, e instanceof AppError, String(e));
5. Errors and testing
Warm-upComputationalA test checks that sortScores([3, 1, 2]) returns [1, 2, 3]. With import assert from "node:assert/strict", which assertion is right?
6. Errors and testing
CoreHumanWhich of these are good error-handling practices in JavaScript? Choose all that apply.
Further reading and resources
- MDN: Error · Mozilla and contributorsThe Error object, its subclasses, and the cause option.
- MDN: try...catch · Mozilla and contributors
- Node.js: Test runner · OpenJS FoundationThe built-in node:test module, its reporters, mocking and coverage.
- Node.js: Assert · OpenJS Foundation
- VitestA popular third-party test framework, common in projects built with Vite.