Production JavaScript, Part 2: Async Error Handling, or How One Missing await Kills Every Request on the Server
A single missing await in one route crashed my test server and took an unrelated user's request down with it. This part of the series runs eight small Node 26 programs that show exactly where errors escape try/catch, what Node does when they do, and the language features and lint rule that catch...
Most beginner JavaScript courses teach error handling as try/catch and move on. In synchronous code, that's most of the story. In async code, which means almost all server-side JavaScript, errors can escape to places a try block never sees: a promise nobody awaited, a callback that runs later on a fresh stack, or an event with no listener. When they escape in Node, the default is to crash the process, which on a server means every request currently in flight dies with it.
This is part 2 of the production JavaScript series. Part 1 covered shutting down cleanly. This part covers not shutting down by accident. Every example is a small program I ran on Node 26.13.1, shown with its real output and exit code, followed by the fix and exercises at the end.
Async Error Handling in Node.js: Where Errors Escape
| Where the error happens | Does an outer try/catch see it? |
Node 26 default |
|---|---|---|
A rejected promise you await |
Yes | Normal exception |
A promise you don't await or .catch() |
No | Process exits with code 1 |
A throw inside a callback (timer, I/O, emitter listener) |
No | Process exits with code 1 |
emitter.emit("error") with no error listener |
It's thrown at the emit call |
Process exits with code 1 if uncaught |
A stream error with .pipe() |
No, and the destination stays open | Leak, or a crash if there's no listener |
A stream error with stream.pipeline() |
Yes, the promise rejects | Normal exception |
The rows that crash are covered one at a time below.
The Forgotten Promise
// An async function that rejects, called without await or .catch().
async function saveAudit() { throw new Error("audit DB is down"); }
saveAudit(); // "fire and forget"
setTimeout(() => console.log("still running 100 ms later"), 100);
### 01-unhandled.mjs
file:///w/01-unhandled.mjs:2
async function saveAudit() { throw new Error("audit DB is down"); }
^
Error: audit DB is down
(exit code 1)
The "still running" line never printed. Since Node 15, an unhandled rejection is treated like an uncaught exception: print the error and exit with code 1. You can switch that behavior back to a warning:
### 01-unhandled.mjs with --unhandled-rejections=warn
(node:1) UnhandledPromiseRejectionWarning: Error: audit DB is down
(node:1) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
still running 100 ms later
(exit code 0)
With --unhandled-rejections=warn, the process logs a warning and carries on. Don't ship that. A rejection nobody handled means something your code believed would happen didn't, and the process keeps running in a state you never designed for, with an audit record missing and nothing to show it. The crash is the honest outcome. The fix is to handle the promise.
One Missing await, Two Users Affected
Here's the same mistake in a server, with a try/catch that looks like it covers everything:
// One route forgets to await. Watch what happens to a completely unrelated request.
import { createServer } from "node:http";
import { setTimeout as sleep } from "node:timers/promises";
async function sendWelcomeEmail() { await sleep(50); throw new Error("SMTP timeout"); }
createServer(async (req, res) => {
try {
if (req.url === "/signup") sendWelcomeEmail(); // missing await: try/catch can't see this rejection
if (req.url === "/report") await sleep(500); // a slow, unrelated request
res.end(`ok ${req.url}\n`);
} catch (err) {
res.statusCode = 500; res.end("handled\n");
}
}).listen(8091, () => console.log("listening"));
I started a slow /report request, then sent /signup 100 ms later:
#!/bin/bash
# Start the server, begin a slow /report request, then hit /signup 100 ms later.
docker rm -f s2 >/dev/null 2>&1
docker run -d --name s2 --network host -v $PWD:/w -w /w node:26-slim node 02-floating-in-server.mjs >/dev/null
for i in $(seq 100); do docker logs s2 2>&1 | grep -q listening && break; sleep 0.1; done
( curl -s -w ' [HTTP %{http_code}]' http://127.0.0.1:8091/report; echo " <- /report, curl exit $?" ) > /tmp/report.txt &
sleep 0.1
echo "$(curl -s -w ' [HTTP %{http_code}]' http://127.0.0.1:8091/signup) <- /signup"
wait; cat /tmp/report.txt
sleep 0.3; echo "server container: $(docker inspect -f '{{.State.Status}}, exit {{.State.ExitCode}}' s2)"
docker logs s2 2>&1 | grep -E '^Error' | sed 's/^/server log: /'
docker rm -f s2 >/dev/null 2>&1
ok /signup
[HTTP 200] <- /signup
[HTTP 000] <- /report, curl exit 52
server container: exited, exit 1
server log: Error: SMTP timeout
/signup returned 200 ok. Its response was already sent before the email promise rejected 50 ms later. Then the rejection, which no code was waiting on, crashed the process. The user on /report, who had nothing to do with signup, got an empty reply (curl exit 52) and the container exited with code 1.
The try/catch didn't help, because sendWelcomeEmail() without await returns a promise immediately and the try block finishes successfully. The rejection happens later, with nothing attached to it. The fix is either await sendWelcomeEmail() (if signup should fail when the email fails) or deliberately detaching it with a handler: sendWelcomeEmail().catch((err) => log.warn(err)). Both are fine. Forgetting is the bug.
We recommend reading JavaScript vs TypeScript: Which One Should You Actually Use? to continue reading our selection of content. TypeScript's type checker plus one lint rule catches this whole class of bug, and here's the case for using it.
JavaScript vs TypeScript: Which One Should You Actually Use? JavaScript vs TypeScript from experience: a production bug types would have caught, what TypeScript adds, and when the compiler is worth it. SudoSecurity · Santhdium
Throws Inside Callbacks
// try/catch only covers the synchronous part. A throw inside a callback runs later, on a fresh stack.
try {
setTimeout(() => { throw new Error("thrown inside a timer callback"); }, 10);
console.log("try block finished without error");
} catch (err) {
console.log("caught:", err.message); // never runs
}
### 03-callback-throw.mjs
try block finished without error
file:///w/03-callback-throw.mjs:3
setTimeout(() => { throw new Error("thrown inside a timer callback"); }, 10);
^
Error: thrown inside a timer callback
(exit code 1)
The try block finished without error, then the timer fired 10 ms later on a new call stack, long after the try was gone. The same applies to any callback-style API: fs.readFile, setImmediate, event listeners and old-style libraries. Wrap the callback-based API in a promise (node:timers/promises, fs/promises, util.promisify) and await it, and the error goes back to being catchable.
EventEmitter's error Event
// An EventEmitter that emits 'error' with no listener throws.
import { EventEmitter } from "node:events";
const queue = new EventEmitter();
queue.on("job", (j) => console.log("processing", j));
queue.emit("job", 1);
queue.emit("error", new Error("broker connection lost"));
console.log("not reached");
### 04-emitter-error.mjs
processing 1
file:///w/04-emitter-error.mjs:6
queue.emit("error", new Error("broker connection lost"));
^
Error: broker connection lost
Emitted 'error' event at:
(exit code 1)
'error' is special in Node's EventEmitter: if nobody's listening, emit("error") throws the error. Message queue clients, database pools, sockets and streams are all emitters, and a broker disconnect at 3 a.m. becomes a process crash if you didn't attach .on("error", ...). Every long-lived emitter you create should get an error listener on the line where it's created.
Wrapping Errors Without Losing Them
When you catch an error to add context, keep the original. ES2022's cause option does that, and the combinators handle several failures at once:
// Wrapping errors without losing the original: error.cause (ES2022).
async function loadUser(id) {
try {
JSON.parse("{not json"); // stand-in for a failing driver call
} catch (err) {
throw new Error(`loadUser(${id}) failed`, { cause: err });
}
}
try {
await loadUser(42);
} catch (err) {
console.log(err.message);
console.log(" cause:", err.cause.name, "-", err.cause.message);
}
// Several things failing at once: Promise.allSettled keeps every result, Promise.any gives an AggregateError.
const tasks = [Promise.reject(new Error("cache miss")), Promise.resolve("db row"), Promise.reject(new Error("api 503"))];
const settled = await Promise.allSettled(tasks);
console.log("allSettled:", settled.map((s) => s.status === "fulfilled" ? s.value : `rejected(${s.reason.message})`).join(", "));
try {
await Promise.any([Promise.reject(new Error("mirror A down")), Promise.reject(new Error("mirror B down"))]);
} catch (err) {
console.log(`any: ${err.name} - ${err.message}: ${err.errors.map((e) => e.message).join(", ")}`);
}
### 05-cause.mjs
loadUser(42) failed
cause: SyntaxError - Expected property name or '}' in JSON at position 1 (line 1 column 2)
allSettled: rejected(cache miss), db row, rejected(api 503)
any: AggregateError - All promises were rejected: mirror A down, mirror B down
(exit code 0)
new Error(msg, { cause })keeps the originalSyntaxErrorattached, so your logs show both "what we were doing" and "what actually broke." Most logging libraries printcausechains automatically now.Promise.allSettlednever rejects. It gives you every outcome, which is right when partial results are useful, like a dashboard with three widgets.Promise.anyresolves with the first success, and if every input fails, it rejects with anAggregateErrorwhoseerrorsarray holds all of them. Use it for "try each mirror."Promise.all(not shown) rejects on the first failure and lets the others keep running unobserved. A common bug is assuming it cancels them. It doesn't.
Streams: .pipe() vs pipeline()
// A source stream fails partway. .pipe() leaves the destination open; pipeline() destroys both and reports the error.
import { Readable, Writable } from "node:stream";
import { pipeline } from "node:stream/promises";
function source() {
let n = 0;
return new Readable({ read() { n++ < 3 ? this.push(`chunk ${n}\n`) : this.destroy(new Error("upstream reset")); } });
}
function sink(name) {
const w = new Writable({ write(chunk, enc, cb) { cb(); } });
w.on("close", () => console.log(` ${name}: destination closed`));
return w;
}
const src1 = source(), dst1 = sink(".pipe()");
src1.on("error", (e) => console.log(` .pipe(): source error "${e.message}"`));
src1.pipe(dst1);
setTimeout(() => console.log(` .pipe(): destination destroyed? ${dst1.destroyed}`), 50);
setTimeout(async () => {
try { await pipeline(source(), sink("pipeline()")); }
catch (e) { console.log(` pipeline(): rejected with "${e.message}"`); }
}, 100);
### 06-pipe-vs-pipeline.mjs
.pipe(): source error "upstream reset"
.pipe(): destination destroyed? false
pipeline(): destination closed
pipeline(): rejected with "upstream reset"
(exit code 0)
With .pipe(), the source failed and the destination was never destroyed: destroyed? false. In a real server, that's an open file handle or a half-written upload that stays around until the process restarts. .pipe() doesn't forward errors, and it doesn't clean up. stream.pipeline() from node:stream/promises destroyed the destination and rejected with the original error, so a plain try/await handles it. Use pipeline() for every chain of streams you create.
Cancellation Is Error Handling Too
A request that should have been abandoned is a slow-motion error. AbortSignal lets you cancel work, and AbortSignal.any() combines several reasons to stop:
// Cancellation: combine a caller's signal with a deadline using AbortSignal.any().
import { setTimeout as sleep } from "node:timers/promises";
async function slowLookup(signal) { await sleep(5000, null, { signal }); return "result"; }
const userCancelled = new AbortController();
const signal = AbortSignal.any([userCancelled.signal, AbortSignal.timeout(300)]);
const t = performance.now();
try {
await slowLookup(signal);
} catch (err) {
console.log(`${err.name} after ${(performance.now() - t).toFixed(0)} ms; signal.reason: ${signal.reason?.name}`);
}
### 07-abort.mjs
AbortError after 300 ms; signal.reason: TimeoutError
(exit code 0)
The lookup was cut off at exactly 300 ms, and signal.reason says which signal fired (TimeoutError rather than a user cancel). In a server, combine the incoming request's signal (closed connection), a deadline and a shutdown signal, then pass the result to every fetch, timer and driver call that accepts one.
We recommend reading Writing Your Own API From Scratch in TypeScript to continue reading our selection of content. For where these patterns sit in a full API, with validation, middleware and logging, this build walks through it.
Writing Your Own API From Scratch in TypeScript Build a production TypeScript API from scratch: authentication, validation, error handling, rate limiting, connection pooling, logging and tests. SudoSecurity · Santhdium
The Safety Net, and What It's For
Some errors will still escape. Install last-resort handlers, but use them to fail well, not to keep going:
// Last-resort handlers: log with context, stop taking traffic, exit non-zero. Never "log and keep going".
import { createServer } from "node:http";
const server = createServer((req, res) => res.end("ok\n")).listen(8092);
function fatal(kind, err) {
console.error(JSON.stringify({ level: "fatal", kind, message: err?.message, stack: err?.stack?.split("\n")[1]?.trim() }));
server.close(() => process.exit(1)); // let in-flight requests finish (see part 1)
setTimeout(() => process.exit(1), 5000).unref(); // but never hang
}
process.on("unhandledRejection", (reason) => fatal("unhandledRejection", reason));
process.on("uncaughtException", (err) => fatal("uncaughtException", err));
setTimeout(() => { Promise.reject(new Error("forgot to await this")); }, 50);
{"level":"fatal","kind":"unhandledRejection","message":"forgot to await this","stack":"at Timeout._onTimeout (file:///w/08-safety-net.mjs:14:35)"}
(exit code 1)
The handler logged one structured line with the error and where it came from, stopped accepting traffic, gave in-flight requests a chance to finish (the pattern from part 1), and exited with code 1 so the platform restarts a clean process. What it must never do is log and carry on. Node's docs on uncaughtException are explicit that it isn't safe to resume normal operation after one, because the process is in an undefined state.
Catch It Before It Runs: no-floating-promises
The forgotten-await bug is mechanical, so a machine can find it. typescript-eslint's no-floating-promises rule uses type information to spot any promise that's created and dropped:
async function sendWelcomeEmail(to: string): Promise<void> {
throw new Error(`SMTP timeout sending to ${to}`);
}
export async function signup(email: string): Promise<string> {
sendWelcomeEmail(email); // floating: nobody awaits or catches this
return "ok";
}
import tseslint from "typescript-eslint";
export default tseslint.config({
files: ["**/*.ts"],
languageOptions: { parser: tseslint.parser, parserOptions: { projectService: true } },
plugins: { "@typescript-eslint": tseslint.plugin },
rules: { "@typescript-eslint/no-floating-promises": "error" },
});
eslint v10.15.0, typescript-eslint 8.74.0, typescript 5.9.3
/w/signup.ts
6:3 error Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator @typescript-eslint/no-floating-promises
✖ 1 problem (1 error, 0 warnings)
It flagged line 6, the exact bug that crashed the server above, before the code ever ran. The rule needs type information, which is what projectService: true provides. I pinned TypeScript 5.9 for the linter, since typescript-eslint runs on the TypeScript compiler API. It's the single most valuable lint rule for server-side TypeScript, and it's worth adding to a JavaScript project by type-checking with JSDoc.
Exercises
- Fix the server. Change
02-floating-in-server.mjsso a failed welcome email is logged but/signupstill returns 200. Then change it so/signupreturns 500 when the email fails. Rerunrun02.shboth times. - Find the floating promises. Add
no-floating-promisesto a project you've written and count the findings. For each one, decide whether it should be awaited, caught or explicitlyvoided. - Make
Promise.allcancel. Write a helper that runs severalfetchcalls with a sharedAbortControllerand aborts the rest when the first one fails. - Stream cleanup. Rewrite an upload handler that uses
req.pipe(fs.createWriteStream(...))to usepipeline(), and prove with a test that a client disconnect midway leaves no open file handle. - Error with context. Take a function that catches and rethrows
new Error("failed"), add{ cause }, and compare what your logger prints before and after.
What This Doesn't Cover
- Framework error middleware. Express 5 forwards rejected async handlers to error middleware. Fastify and Hono have their own models, and it's worth knowing what yours does with a promise it never sees.
- Error monitoring services. Sentry and similar tools hook the same process events shown here.
- Worker threads and child processes. Errors there cross a boundary as messages and need their own handling.
- Browser JavaScript.
unhandledrejectionexists in browsers too, but a page doesn't crash. It just quietly breaks.
The Actual Point
In async JavaScript, try/catch only sees errors from code you await. Everything else, including dropped promises, callback throws and emitter errors without listeners, goes straight to the process, and Node's correct, unforgiving default is to exit. One forgotten await in a signup route crashed a server and took an unrelated user's request with it. Await or explicitly handle every promise, wrap callback APIs in promises, put an error listener on every emitter, use pipeline() for streams, keep causes when you wrap errors, and let a lint rule find the ones you'll miss. Then install a safety net that fails cleanly, because something will still get through.
Sources: the Node.js v26 documentation for process events (unhandledRejection, uncaughtException), the --unhandled-rejections CLI flag, events, streams and AbortSignal, and the typescript-eslint no-floating-promises rule docs. All examples were run by me on node:26-slim, with eslint 10.15.0, typescript-eslint 8.74.0 and TypeScript 5.9.3 for the lint example. Every code and output block above is reproduced verbatim from those runs; the programs are original teaching code using Node's public API.
$ tail -f /forums
Discussion
Comments live on the community forums — sign in there to reply.