Error handling patterns
The try statement says nothing about where it belongs, and most bad error handling is a catch in the wrong place: too deep to add anything, too wide to know what failed, or too eager and turned into a printed line that the program then forgets. The patterns in this lesson are the four that cover almost every case.
The first collects every validation problem before it throws, the second wraps a failure with the operation that failed and keeps the original, the third is the code that deliberately has no catch at all, and the fourth is the one boundary at the edge of the program where a message and an exit code are the whole answer.
Every problem in one pass
A form with four fields and four mistakes should say all four, not one per attempt. The way to do that is to return a list of problems from the check and throw once, at the point where the caller can no longer do anything: AggregateError carries that list in its errors field.
The file collect.mjs:
function validate(user) {
const problems = [];
if (!user.name) {
problems.push('the name is empty');
}
if (!user.email.includes('@')) {
problems.push('the email has no @');
}
if (user.age < 0) {
problems.push('the age is negative');
}
return problems;
}
const user = { name: '', email: 'nobody', age: -3 };
const problems = validate(user);
console.log('problems found:', problems.length);
for (const problem of problems) {
console.log('-', problem);
}
try {
throw new AggregateError(problems.map((text) => new Error(text)), 'the user is not valid');
} catch (error) {
console.log('the summary:', error.message);
console.log('the parts:', error.errors.length);
}
node collect.mjs
problems found: 3
- the name is empty
- the email has no @
- the age is negative
the summary: the user is not valid
the parts: 3
Three checks ran on one pass and produced three lines, and the throw at the end turned the same list into one value with a summary and a part for each problem. A validator that returns the list and lets the caller decide is the more useful half of this: a form prints the lines, a command line throws them.
Wrap and rethrow
A layer that knows what the program was doing should say so. The catch below reads the low-level failure, throws a new error whose message names the operation, and passes the original as the cause: nothing is lost, and the message a user reads is about the record rather than about a parse.
The file rethrow.mjs:
function parseAge(text) {
const value = Number(text);
if (Number.isNaN(value)) {
throw new Error(`the age is not a number: ${text}`);
}
if (value < 0) {
throw new RangeError(`the age is negative: ${value}`);
}
return value;
}
function loadRecord(text) {
try {
return { age: parseAge(text) };
} catch (error) {
throw new Error('the record could not be read', { cause: error });
}
}
for (const text of ['42', 'x', '-1']) {
try {
console.log('age:', loadRecord(text).age);
} catch (error) {
console.log(`${error.message}: ${error.cause.message}`);
}
}
node rethrow.mjs
age: 42
the record could not be read: the age is not a number: x
the record could not be read: the age is negative: -1
The two failures reached the top with the same outer message and different causes, and the last log line printed both layers. Without the cause the range error and the parse error would look identical from here, which is the point of wrapping rather than replacing.
When not to catch
A function that cannot fix a failure, name it better or clean anything up should let it pass. A catch that only logs and returns a default hides the failure from the caller, which is how a program ends up printing a wrong number instead of stopping. The functions below have no catch at all, and the loop that calls them has one.
The file nocatch.mjs:
function divide(left, right) {
if (right === 0) {
throw new RangeError('division by zero');
}
return left / right;
}
function average(values) {
let total = 0;
for (const value of values) {
total += value;
}
return divide(total, values.length);
}
for (const values of [[2, 4], [10], []]) {
try {
console.log(`average of ${values.length}:`, average(values));
} catch (error) {
console.log(`average of ${values.length} failed: ${error.name}: ${error.message}`);
}
}
node nocatch.mjs
average of 2: 3
average of 1: 10
average of 0 failed: RangeError: division by zero
The empty list divided zero by zero and the throw travelled through two frames without a handler in either, which is what a function that has nothing to add should do. The caller caught it, printed the kind and the message and kept the other two cases running: in a loop over records, that is the difference between one bad line and a stopped import.
One boundary at the edge
A program with a command line needs one catch, near the top, that turns an error into a message on standard error and a code the shell can read. Everything below it throws and adds context. The block below wraps the call to main, prints the message and sets process.exitCode, which ends the process with that code once the current work is done.
The file boundary.mjs:
function main(args) {
if (args.length === 0) {
throw new Error('usage: boundary.mjs NAME');
}
return `hello ${args[0]}`;
}
try {
console.log(main(process.argv.slice(2)));
} catch (error) {
console.error(`error: ${error.message}`);
process.exitCode = 1;
}
node boundary.mjs 2>&1
echo "exit code: $?"
node boundary.mjs Ada 2>&1
echo "exit code: $?"
error: usage: boundary.mjs NAME
exit code: 1
hello Ada
exit code: 0
The command merges the two streams so that the block shows the order, and the first run printed one line on standard error and left one as its code; the second printed the answer and left zero. That single catch is also where a program decides which errors are worth a stack: the message is enough for a usage error, while an unexpected one should print all of it.
Exercises
- Add a fourth rule to the validator and a fourth problem to the user. How many parts does the aggregate error have?
- Make loadRecord print the cause and rethrow the same error instead of a new one. Which message reaches the caller then?
- Wrap the loop of the third program in its own try and see what one failing iteration does to the rest.
- Change process.exitCode to process.exit(1) and add a log line after the catch. Does the line print?
- Write a small function that validates a name and returns the list of problems without throwing, and use it to print all of them in one line.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why collect validation problems and throw once?
Answer
The caller can report every problem in one pass
One pass over the data finds all the mistakes, and one throw at the end reports them together.
-
What does AggregateError add to a normal error?
Answer
A list of errors in its errors field
The aggregate carries the parts, and its own message is the summary.
-
What does wrapping an error with cause keep?
Answer
The operation that failed and the original error
The new message names the layer, and cause keeps the reason from the layer below.
-
When should a function let an error pass without a catch?
Answer
When it cannot fix the failure or say anything new about it
A catch that adds nothing hides the failure from the caller, which is the code that can act on it.
-
What does this program print?
function check(n) { const problems = []; if (n < 0) problems.push("negative"); if (n > 10) problems.push("too large"); return problems; } console.log(check(-1).length, check(20).length, check(5).length);Answer
1 1 0
Each call checks its own number, and one rule fires for the first two and none for the last.
-
What does this program print?
try { throw new AggregateError([new Error("a"), new Error("b")], "two problems"); } catch (error) { console.log(error.message, error.errors.length); }Answer
two problems 2
The message is the summary and the errors field holds the two parts.
-
What does this program print?
function outer() { try { throw new RangeError("low"); } catch (error) { throw new Error("the record failed", { cause: error }); } } try { outer(); } catch (error) { console.log(error.message, "|", error.cause.name); }Answer
the record failed | RangeError
The outer message is the one of the wrapper, and the cause is still the original range error.
-
What does this program print?
function divide(a, b) { if (b === 0) throw new RangeError("division by zero"); return a / b; } try { console.log(divide(6, 2)); console.log(divide(1, 0)); console.log("not printed"); } catch (error) { console.log(error.message); }Answer
3 / division by zero
The first call prints its value, the second throws, so the third line of the try never runs.
-
What does
process.exitCode = 1do?Answer
Ends the process with 1 when the current work is done
The code is recorded and used at exit, unlike process.exit, which stops the work at once.
-
Where does the one catch of a small command line program belong?
Answer
At the top, around the call to main
The edge of the program is where a message and an exit code make sense, and the layers below add context.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev