Sub topic 10
Why try/catch Misses Errors in Later Callbacks
This chapter assumes you can write functions and pass them as arguments, you know what setTimeout does, and you have used try and catch on ordinary synchronous code. It explains one of the most common surprises in JavaScript error handling. Code can sit inside a try block on the page and still throw an error that the catch never sees.
The surprise
Here is the classic case:
try {
setTimeout(() => {
throw new Error('boom');
}, 0);
} catch (err) {
console.log('This never runs');
}Run it in Node.js and the process crashes with Error: boom. Run it in a browser and the console shows Uncaught Error: boom. The catch block never runs, even though the throw statement sits inside the braces of the try.
To see why, separate two ideas. Where code is written in the source file is one thing. When that code actually runs is another. try/catch only cares about the second.
The working model: try/catch guards a span of time on the call stack
The call stack is the list of functions that are currently running. Each call adds a frame on top of the stack, and each return removes one. When code throws, the JavaScript engine unwinds the stack frame by frame, looking for an active try block whose catch can take the error.
A try block is active only while its code is executing. Once execution leaves the closing brace of the try, that handler is gone. Nothing records it for later.
Now trace the setTimeout example:
- The engine enters the
tryblock. setTimeoutis called. It hands the arrow function to the host environment (the browser or Node.js) along with a delay, then returns at once. It does not call the arrow function.- The
tryblock finishes with no error. Thecatchis skipped, and the handler is no longer active. - The rest of the script runs, and the call stack empties.
- Later, the event loop, the mechanism that pulls waiting work from queues and runs it, takes the timer callback from the task queue and calls it on a fresh, empty stack.
- The callback throws. The engine unwinds the stack and finds no active
try, because the only frames below the callback belong to the event loop itself. The error is uncaught.
The delay does not matter. A delay of 0 still means "run after the current code finishes," so the timing problem is identical to a delay of five seconds.
Callback timing decides the outcome, not the fact that it is a callback
Not every callback escapes try/catch. What matters is whether the function you pass runs synchronously, during the call that receives it, or asynchronously, at some later point.
try {
[1, 2, 3].forEach((n) => {
if (n === 2) throw new Error(`bad item: ${n}`);
});
} catch (err) {
console.log('Caught:', err.message); // Caught: bad item: 2
}forEach calls its callback right away, while the try block is still on the stack, so the error unwinds into the catch as usual. The same is true of map, filter, sort comparators, and most other array methods.
| API | When the callback runs | Caught by a surrounding try/catch? |
|---|---|---|
| `Array.prototype.forEach`, `map`, `filter` | Synchronously, during the call | Yes |
| `setTimeout`, `setInterval` | Later, as a task | No |
| `addEventListener` handlers | Later, when the event fires | No |
| Node.js `fs.readFile` callback | Later, when I/O completes | No |
| `queueMicrotask` | Later, as a microtask | No |
| `.then()` callbacks | Later, as a microtask | No (becomes a rejection) |
| `new Promise` executor | Synchronously | No (throw becomes a rejection) |
The last two rows are a different case. Promises catch errors themselves, as described below.
When you are unsure about an API, check its documentation or test it. Log something just before the call, inside the callback, and just after the call. If "after" prints before "inside," the callback is asynchronous.
console.log('before');
someApi(() => console.log('inside'));
console.log('after');The fix: put the try/catch where the code runs
The try block has to be on the stack when the error is thrown. For asynchronous callbacks, that means moving it inside the callback:
setTimeout(() => {
try {
throw new Error('boom');
} catch (err) {
console.log('Caught inside the callback:', err.message);
}
}, 0);The same applies to event handlers. A try wrapped around addEventListener protects only the act of registering the handler. It does nothing for the handler's later runs.
const button = document.querySelector('#save');
button.addEventListener('click', () => {
try {
saveForm();
} catch (err) {
showErrorBanner(err.message);
}
});If many callbacks need the same handling, write a small wrapper instead of repeating the try in each one:
function safely(fn, onError) {
return function (...args) {
try {
return fn.apply(this, args);
} catch (err) {
onError(err);
}
};
}
const logError = (err) => console.error('Callback failed:', err.message);
setTimeout(safely(() => {
throw new Error('timer failed');
}, logError), 0);
// Callback failed: timer failedThe wrapper returns a new function. When the host later calls that function, the try inside it is on the stack, so the error is caught.
Node.js error-first callbacks
Older Node.js APIs never relied on try/catch for asynchronous failures. Instead, they pass the error to the callback as its first argument. This convention is called an error-first callback.
const fs = require('fs');
try {
fs.readFile('/no/such/file.txt', 'utf8', (err, data) => {
if (err) {
console.error('Read failed:', err.code); // Read failed: ENOENT
return;
}
console.log(data);
});
} catch (err) {
console.log('Never reached for I/O errors');
}The outer try here is useless for the file-not-found case, because the read fails long after readFile has returned. The if (err) check inside the callback is the real error handling. It is easy to forget it, and the failure is then silently ignored.
Watch out for one gotcha. If your own code inside the callback throws, for example by calling JSON.parse(data) on bad content, that error is not passed to anyone. It is thrown on a fresh stack and becomes an uncaught exception. Error-first handling covers the operation's failure, not bugs in your callback body. Wrap risky work inside the callback in its own try.
Promises catch errors in a different way
Promise callbacks also run later, so an outer try cannot catch their errors either. The difference is that promises do not let those errors escape as uncaught exceptions right away. A throw inside a .then() callback, or inside a new Promise executor, is captured and turned into a rejected promise.
try {
Promise.resolve().then(() => {
throw new Error('inside then');
});
new Promise(() => {
throw new Error('inside executor');
});
} catch (err) {
console.log('Never runs for either error');
}Neither error reaches the catch. The executor runs synchronously, but the Promise constructor catches its throw and rejects the promise instead of rethrowing. Because nothing handles these rejected promises, the environment reports them as unhandled rejections. Recent Node.js versions terminate the process for this, and browsers log a warning.
This is not a reason to avoid promises. Rejections travel along the promise chain, so you can handle them at a chosen point instead of inside each callback. The next two chapters cover .catch() and await, which put errors back within reach of ordinary try/catch.
Common mistakes
- Wrapping the registration instead of the work. A
tryaroundsetTimeout,setInterval,addEventListener, orreadFileprotects only the call that registers the callback. - Assuming a zero delay makes code synchronous.
setTimeout(fn, 0)still runsfnafter the current stack empties. - Ignoring the
errargument. With error-first callbacks, an uncheckederrmeans the failure disappears anddataisundefined. - Thinking a promise executor is protected by an outer try. The executor runs synchronously, but its errors become rejections, not exceptions.
- Mixing styles. Throwing inside an error-first callback to "send" the error to an outer handler does not work. Pass it to another callback or convert the API to promises instead.
Exercise
The code below is meant to log "Handled" when the interval callback fails, but the process crashes instead. Explain why, and rewrite it so the failure is handled and the interval is stopped. try { const id = setInterval(() => { throw new Error('tick failed'); }, 100); } catch (err) { console.log('Handled'); }
Show answer
setInterval only registers the callback and returns immediately, so the try block finishes before the first tick. Each tick runs on a fresh call stack with no active try, so the error is uncaught. Move the try/catch into the callback and clear the interval there: const id = setInterval(() => { try { throw new Error('tick failed'); } catch (err) { console.log('Handled:', err.message); clearInterval(id); } }, 100);
Exercise
For each snippet, say whether the outer catch runs: (a) try { [3, 1].sort(() => { throw new Error('x'); }); } catch (e) { ... } (b) try { queueMicrotask(() => { throw new Error('x'); }); } catch (e) { ... } (c) try { new Promise(() => { throw new Error('x'); }); } catch (e) { ... }
Show answer
(a) Yes. sort calls the comparator synchronously while the try is active. (b) No. The microtask runs after the current script finishes, on a fresh stack, so the error is uncaught. (c) No. The executor does run synchronously, but the Promise constructor catches the throw and rejects the promise, so nothing is thrown to the outer try. The result is an unhandled rejection.
Exercise
In a Node.js fs.readFile callback, you check if (err) and return early, then call JSON.parse(data). The file exists but contains invalid JSON. What happens, and how do you fix it?
Show answer
The read succeeds, so err is null and the check passes. JSON.parse then throws a SyntaxError inside the callback, which runs on a fresh stack, so the error is uncaught and the process exits. Wrap the parsing in its own try/catch inside the callback: try { const config = JSON.parse(data); ... } catch (parseErr) { console.error('Bad JSON:', parseErr.message); }