Errors in asynchronous code
An async function does not throw to its caller: it rejects the promise it returned, and the caller sees a throw only where it awaits. That one sentence explains both the propagation that works and the failure that does not, the promise nobody awaited.
The lesson follows a failure up a chain of awaits, shows what Node.js does with a rejection that nobody handles, writes the top-level try that turns it into a message and an exit code, and ends with a report over many calls where a failure is data. The two programs that fail have the exit code in their output block.
An error travels up through await
When an awaited promise rejects, the await throws inside the async function, and the promise that function returned rejects in turn. The error climbs the chain of awaits until a try catches it, and none of the functions in between needs a line of handling code.
The file propagate.mjs:
const delay = (value, ms) =>
new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
async function load(name) {
await delay(null, 10);
if (name === '') {
throw new Error('the name is empty');
}
return `loaded ${name}`;
}
async function report(name) {
const text = await load(name);
return text.toUpperCase();
}
try {
console.log(await report('notes.txt'));
console.log(await report(''));
} catch (error) {
console.log('the top caught:', error.message);
}
node propagate.mjs
LOADED NOTES.TXT
the top caught: the name is empty
The upper case line is there to show that the first report did its own work: report called load, turned the text around and returned. The second call threw one layer down, and the throw came out of the await in report and then out of the await in the top-level block.
The unhandled rejection
A promise that rejects with no handler is an unhandled rejection. Node.js reports it on standard error with the message and the stack, and ends the process with one: since version 15 the default is to treat it as a fatal error rather than a warning.
The file unhandled.mjs:
async function load() {
throw new Error('nobody catches this');
}
console.log('the call is not awaited');
load();
console.log('this line still runs');
node unhandled.mjs
echo "exit code: $?"
the call is not awaited
this line still runs
exit code: 1
Both lines printed, because the rejection happens in a microtask after them, and then the process ended with one. The message on standard error is the error itself with the stack that reached the call of load, which is why the block above keeps to standard output and the code.
The top-level try and the exit code
A module can await at the top level, so the same boundary as in the lesson on patterns works here: one try around the call to main, a message on standard error and a code. A usage error and an unexpected failure can be given different codes, and a script that calls the program can tell them apart.
The file boundary.mjs:
const delay = (value, ms) =>
new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
async function main(argv) {
await delay(null, 10);
if (argv.length === 0) {
throw new Error('usage: boundary.mjs FILE');
}
return `read ${argv[0]}`;
}
try {
console.log(await main(process.argv.slice(2)));
} catch (error) {
console.error(`error: ${error.message}`);
process.exitCode = 2;
}
node boundary.mjs 2>&1
echo "exit code: $?"
node boundary.mjs notes.txt 2>&1
echo "exit code: $?"
error: usage: boundary.mjs FILE
exit code: 2
read notes.txt
exit code: 0
The command merges the two streams so that the block shows the order: the failed run printed one line and left two as its code, and the successful one printed its answer and left zero. Two is a common choice for a usage error, which is the code a shell script reads before it decides whether to try again; the point is that the program chose it rather than the runtime.
A report over many calls
When a program makes many calls and one bad item should not stop the rest, the failure belongs in the data. allSettled from the lesson on combinators gives one result per call, and the loop over those results decides what to print. The program below copies three names and one of them is refused.
The file settle.mjs:
const delay = (value, ms) =>
new Promise((resolve) => {
setTimeout(() => resolve(value), ms);
});
async function load(name) {
await delay(null, 10);
if (name.endsWith('.bin')) {
throw new Error(`${name} is binary`);
}
return name;
}
const results = await Promise.allSettled(['a.txt', 'b.bin', 'c.txt'].map((name) => load(name)));
for (const result of results) {
if (result.status === 'fulfilled') {
console.log('loaded:', result.value);
} else {
console.log('failed:', result.reason.message);
}
}
node settle.mjs
loaded: a.txt
failed: b.bin is binary
loaded: c.txt
All three calls ran, the failure was printed in its place, and the two good names were loaded. That is the shape of a batch job: one report, every item accounted for, and a decision at the end about the exit code. The next lesson reads a sequence of values that arrive one after another with for await.
Exercises
- Add a catch around the second report call only. Which lines print now?
- Put load() behind an await in the unhandled program. What changes in the output and in the exit code?
- Give the boundary program a different code for a validation error and a generic one, and check both in the shell.
- Change the report program to count the failures and set the exit code to the number of them.
- Use finally in the boundary program to print a last line on both paths. Which line is printed for the failure?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does an unhandled rejection do in Node.js?
Answer
It prints the error and ends the process with 1
The default since version 15 is a fatal error, and the exit code is one.
-
How does an error travel through a chain of awaits?
Answer
It rejects each async function until a try catches it
Each awaited promise rejects in turn, so one try at the top handles a failure from any depth.
-
What does
process.exitCode = 2do at the end of a program?Answer
It makes the process exit with 2
The code is recorded and used when the process ends, so the work in flight still finishes.
-
Why is a call to an async function without await dangerous?
Answer
A rejection of it has no handler
Nothing is attached to the returned promise, so a failure becomes an unhandled rejection.
-
What does this program print?
async function f() { throw new Error("x"); } try { await f(); } catch (error) { console.log("caught", error.message); }Answer
caught x
The await turns the rejection into a throw, and the catch prints both words.
-
What does this program print?
async function a() { throw new RangeError("low"); } async function b() { return a(); } try { await b(); } catch (e) { console.log(e.name); }Answer
RangeError
The rejection of a travels through b without a handler, and the name survives the trip.
-
What does this program print?
try { await Promise.reject(new Error("no")); } catch (error) { console.log(error.message); } finally { console.log("done"); }Answer
no / done
The catch prints the message and the finally runs after it.
-
What does this program print?
const results = await Promise.allSettled([Promise.resolve("a"), Promise.reject(new Error("b"))]); console.log(results[1].reason.message);Answer
b
The second result is the rejected one, and its reason holds the error.
-
What exit code does a program leave after
process.exitCode = 2?Answer
2
The recorded number is the code of the process, and one is only the default for a failure.
-
Why is an unhandled rejection worse in a server than in a script?
Answer
The process exits while requests are still in flight
The default is a fatal error, so one forgotten catch stops every request the process was serving.
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