Lesson 6 of 14 · 25m
Async Errors: Rejections, try/catch, and the Boundary
An async function never throws — it returns a rejection nobody awaits, which since Node 15 ends the process.
An async function never throws. It returns a promise, and when something inside it fails, that promise rejects — a value sitting in a queue, not an exception propagating through a stack. If nobody awaits or catches it, you have a rejection nobody saw, and since Node 15 that's a process-ending event by default.
try/catch only sees what it awaits
try {
const p = fetchReport(); // returns a promise — nothing thrown yet
} catch (err) {
// never runs: the failure hasn't happened, and isn't an exception anyway
}The catch guards the synchronous portion of the expression — the call itself. To catch the rejection, you must await (or attach .catch):
try {
await fetchReport();
} catch (err) {
// now it runs — await unwraps the rejection into a thrown value
}The same rule explains the most common async bug in the wild: items.forEach(async item => { ... }). forEach never awaits; each callback returns a promise nobody holds, so every failure inside is an unhandled rejection. Use for...of (sequential) or map + Promise.all / allSettled (parallel) instead.
Rejections that kill the process
Node's default since Node 15 is --unhandled-rejections=throw: a rejected promise with no handler terminates the process. That is correct behavior — a rejection nobody caught is a bug, and Node refuses to keep running a process in an unknown state. But it means every fire-and-forget .map(async …), every dropped Promise.race loser, every queue drain nobody awaited is a 3 a.m. outage in waiting. The fix isn't process.on('unhandledRejection', () => {}) — registering the listener prevents the crash but converts a loud failure into a silent one. Use the listener for telemetry and graceful shutdown, and make sure every promise you create is genuinely handled:
queue.drain().catch(err => log.error('drain failed', { err }));.catch itself returns a promise — one that resolved, unless the handler threw. Chained .catch swallows; if you logged and want the caller to still see failure, rethrow. p.finally(f) is a different tool — it runs f on settle without seeing the value and without swallowing, so a rejection stays rejected: finally is cleanup, not handling. And the flags exist for the process-level default: --unhandled-rejections=warn restores the pre-15 "log and limp on" behavior and none silences it entirely — both convert the bug from loud to silent rather than fixing it.
Errors worth throwing
Error subclasses let callers distinguish "expected failure" from "bug":
class UpstreamError extends Error {}
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.field = field;
}
}instanceof works on real classes in modern runtimes. ES2022 added cause, which replaces the old log-and-lose pattern:
throw new Error('charge failed', { cause: stripeErr });Now err.cause retains the original error — its stack included — instead of a stringified summary that deleted it. And AggregateError (ES2021) is how Promise.any reports "everything failed," with all reasons in .errors.
At the API boundary: translate, don't relay
Your err object is not your response body. err.stack is a stack trace with your file paths; err.message may contain a SQL fragment or an internal URL. The Express error middleware exists for exactly this — and its signature's four arguments are load-bearing:
app.use((err, req, res, next) => { // arity IS the dispatch: 4 args = error handler
const status = err instanceof ValidationError ? 422 : 500;
const id = crypto.randomUUID();
log.error({ err, id }); // full detail to your logs
res.status(status).json({ error: 'request failed', id }); // opaque detail to them
});A three-argument function in that position is a normal middleware that skips errors entirely — the arity is the contract. Map your domain errors to status codes at the edge, give the client a correlation ID, and keep internals in the logs.
The wrong mental model
People picture async errors as exceptions that "bubble." Nothing bubbles — a rejection is a result in a queue, and the only thing connecting it to your catch is the await you wrote. The practice: await what you call, handle or deliberately .catch every promise, wrap with cause instead of stringifying, and translate errors once at the boundary — never serialize err to a client.
Try this
Write an endpoint that calls a failing upstream inside try { fetchUpstream() } catch {} — without await — then fire requests and watch the process die on unhandledRejection anyway. Add the await, then a .catch that logs and rethrows, and finally a real error middleware. Watch which layer each failure reaches.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Angular 18: Deferred Views & Built-in Control Flow
The newest release of Angular – which is Angular 18 – is planned to be released on May 22nd, 2024. This is Google's super popular TypeScript based webapp framework that allows developers to create amazing web applications. The features, changes, and goodies of this release are deferrable views…
Angular 15: Simplifies Development Promises
Angular 15, a planned upgrade to Google’s TypeScript framework for web development, will stabilize standalone component APIs, simplifying application building, and offer a new way to compose UI logic, the company announced. Angular 15 is expected to arrive in November, said Minko Gechev, Google…
Angular 14 is Now Released
Angular 14, the latest version of the Google-developed, TypeScript-based web application framework, has arrived, featuring typed forms and a developer preview of standalone components. Standalone components simplify the development of Angular applications by reducing the need for NgModules.…
Node Runs TypeScript Now. Here's Exactly What It Strips, What It Refuses, and What It Costs
Node 24 and 26 run .ts files with no build step and no flags, by replacing types with whitespace. I ran eleven test cases, the TypeScript 7 compiler and tsx against both versions: enums, parameter properties and type imports without the type keyword all break, type errors run anyway, and...