Failures That Cross an Async Boundary
An error thrown in a callback, a timer or an event handler cannot reach the try block that started the work, because that stack is already gone.
try/catch only covers the stack frame it is on. A throw inside setTimeout, an event listener or a detached promise has no caller to unwind to. Each has a different correct answer, and the global handlers exist to tell you when you missed one.
EXERCISE
1Where try Cannot Follow
Three shapes that look covered and are not, and the reason is the same in all three.
try/catch catches whatever unwinds through it while it is on the stack. The moment work is deferred, the original stack is gone and there is nothing to unwind into.
A timer callback:
try {
setTimeout(() => {
throw new Error("from the timer");
}, 0);
} catch (err) {
console.log("never runs");
}
// Uncaught Error: from the timer
setTimeout returned immediately and the try block finished. When the callback ran, it ran from an empty stack, called by the event loop. The try was not merely out of scope; it no longer existed.
An event listener:
try {
button.addEventListener("click", () => {
throw new Error("from the click");
});
} catch (err) {
console.log("never runs");
}
Same reason. addEventListener returned, the click happened much later, and the browser invoked the handler with nothing beneath it.
A detached promise:
try {
save(data); // async, not awaited
} catch (err) {
console.log("never runs");
}
This one is Unit 6's point again. save returned a promise and the try completed before it rejected.
The unifying rule:
// try/catch covers the CURRENT stack.
// If the failure happens on a later turn of the event loop,
// it happens on a different stack, and a try cannot see it.
Which gives three different fixes, because the three shapes differ:
// Timer or listener: the try goes INSIDE, where the stack is.
setTimeout(() => {
try {
risky();
} catch (err) {
report(err);
}
}, 0);
// Detached promise: await it, or attach a catch.
await save(data);
save(data).catch(report);
// Async callback in a listener: try inside the callback.
button.addEventListener("click", async () => {
try {
await submitForm();
} catch (err) {
showError(err);
}
});
Each one puts the handler where the failing stack actually is. There is no way to reach backwards.
And one that is easy to miss, inside a promise executor:
new Promise((resolve) => {
setTimeout(() => {
throw new Error("lost"); // NOT a rejection, just uncaught
}, 0);
});
The constructor converts a synchronous throw into a rejection, as Unit 5 showed. It cannot do that for a throw on a later turn, because the executor has long since returned. Call reject instead:
new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error("handled"));
}, 0);
});
EXERCISE
2The Handlers of Last Resort
Two global hooks catch what nothing else did, and their job is reporting rather than recovery.
In the browser:
window.addEventListener("error", (event) => {
report({ message: event.message, stack: event.error?.stack });
});
window.addEventListener("unhandledrejection", (event) => {
report({ message: String(event.reason) });
event.preventDefault(); // suppress the console warning
});
error covers synchronous throws that reached the top. unhandledrejection covers promises that rejected with no handler attached. You need both; neither covers the other.
In Node, with an important difference:
process.on("uncaughtException", (err) => {
logger.fatal(err);
process.exit(1); // shut down, do not continue
});
process.on("unhandledRejection", (reason) => {
logger.error(reason);
process.exit(1);
});
Since 15 an unhandled rejection terminates the process by default. Handling the event so you can log it and then choosing to exit anyway is deliberate: after an uncaught exception the process is in an unknown state, and continuing risks corrupting data with code that thinks everything is fine.
When a rejection counts as unhandled:
const p = Promise.reject(new Error("boom"));
// the warning fires once the microtask queue drains
setTimeout(() => {
p.catch(() => {}); // works, but the warning already happened
}, 0);
The check happens at the end of the current turn. Attaching a handler in a later macrotask still prevents the crash in some runtimes and still reports the warning, which is why attaching handlers late is not a strategy.
What these handlers are for, and what they are not:
// FOR: knowing that a bug exists, with enough detail to fix it.
// Sending to an error tracker. Logging with context.
// Showing the user a generic failure screen.
//
// NOT FOR: recovery. If you could recover, you would have
// caught it where it happened and known what to do.
A global handler that swallows everything and carries on produces an application that is broken in ways nobody can see, which is worse than one that stops.
And in a framework, there is usually a layer between:
// React error boundaries catch render-time throws in a subtree
// and let you show a fallback instead of a blank page.
//
// They do NOT catch errors in event handlers, timers, or async
// code, for exactly the reason in the last exercise: those run
// on a different stack from the render.
That exception surprises people constantly, and it is the same rule rather than a framework quirk.
Pro Tip: Wire up both global handlers on day one of any project, before you think you need them. They cost four lines and they are the difference between a bug report that says "it broke" and one that arrives with a stack trace. Treat every error reaching them as a missing
catchsomewhere, and go and add it.
EXERCISE
3Choosing Where the Boundary Goes
Catching in the right place matters more than catching well, and there are only a few places that are right.
Most error-handling problems are placement problems. The code catches, it just catches somewhere that cannot do anything useful.
Catch where you can act, not where the failure happened:
// Too low: this function cannot decide what should happen
async function fetchUser(id) {
try {
return await api.get(`/users/${id}`);
} catch (err) {
console.log(err);
return null; // every caller now gets a silent null
}
}
// Better: let it through, and catch where the decision lives
async function fetchUser(id) {
return api.get(`/users/${id}`);
}
async function showProfile(id) {
try {
render(await fetchUser(id));
} catch (err) {
showProfileError(err); // this layer knows what the user sees
}
}
The lower function returning null on failure is the more damaging version, because the caller cannot tell "no such user" from "the network is down".
Three placements that are usually right:
// 1. At the entry point of a user action.
button.addEventListener("click", async () => {
try {
await submitForm();
} catch (err) {
showError(err);
}
});
// 2. At a boundary where you translate foreign failures into yours.
async function apiRequest(url) {
try {
return await fetch(url);
} catch (err) {
throw new TransientError("Network unavailable", { cause: err });
}
}
// 3. Around something you must clean up, with no catch at all.
const connection = await pool.acquire();
try {
return await work(connection);
} finally {
connection.release();
}
Everything between those points should generally let errors pass. A function in the middle that catches is usually converting a clear failure into an ambiguous one, because it has less information than either the layer below or the layer above.
A rule that holds up well:
// Catch when you can do exactly one of:
// change what the user sees
// add context and rethrow
// release a resource
//
// If none of the three applies, do not catch.
And the shape that causes the most trouble:
async function loadEverything() {
try {
const user = await fetchUser();
const posts = await fetchPosts(user.id);
const stats = await computeStats(posts);
render(user, posts, stats);
} catch (err) {
showError("Something went wrong");
}
}
One catch around four operations. It works, and when a user reports the message you cannot tell which of the four failed, or whether computeStats threw a TypeError because of a bug. Either narrow the try, or use cause at each step so the log can say.
Pro Tip: Ask what you would do differently in the
catchbefore writing it. If the honest answer is "log it and carry on as though nothing happened", the handler is not helping and the error would be more useful left alone, where the global handler will at least report it with a full stack.
