In a Node.js service, an error several awaits deep keeps its callers in the stack, but one from a callback-based driver, or under deep middleware, shows only library frames. Why, and what helps?
answer
- captured at construction time
- only the current tick's frames
- awaiting async functions get appended
- ten frames by default
- source maps for transpiled code
basics
~20 sAn Error captures only the current tick's frames when created. Along an await chain V8 appends the awaiting async functions; a driver callback runs on a fresh tick with no link back. Promisify, await and wrap at the boundary.
solid answer
~50 s`error.stack` is captured when the `Error` is constructed, and Node's errors documentation says the frames are bounded by `Error.stackTraceLimit` or the frames available on the current event loop tick, whichever is smaller. Along an `await` chain V8 can reconstruct the async functions waiting on the current one and append them, so you still see your route handler. A callback-based driver calls you, or builds its error, from a later tick started by an I/O completion; nothing connects that tick to the code that issued the query, so only driver frames remain. Fixes: promisify the driver and `await` it, then wrap its error in a new `Error` created in your own async function (with `cause`); raise `Error.stackTraceLimit` or pass `--stack-trace-limit` when frames are cut at the default of 10; use `--enable-source-maps` for transpiled code; carry the request id in `AsyncLocalStorage`.
code
javascript · 21 linesimport { promisify } from 'node:util';
function legacyQuery(sql, cb) { // a callback-style driver
setImmediate(() => cb(new Error('connection reset')));
}
const query = promisify(legacyQuery);
async function findOrder(id) {
try {
return await query(`select ... ${id}`);
} catch (err) {
throw new Error(`findOrder(${id}) failed`, { cause: err });
}
}
async function handler() { await findOrder(7); }
handler().catch((e) => {
console.log(e.stack); // names findOrder and the awaiting handler
console.log(e.cause.stack); // starts at the setImmediate callback
});go deeper
Recall that a stack trace is recorded when the Error is created and that the default limit is ten frames.
Explain why a callback from I/O starts a new stack while an await chain can still show its async callers.
Diagnose a broken trace: tell truncation from a callback boundary, then promisify, wrap with cause at the boundary, and enable source maps for transpiled builds.
Set the service defaults: a moderate stack limit in NODE_OPTIONS, source maps in production builds, and a rule that driver errors are wrapped at the repository boundary.
## When the stack is captured Every built-in `Error` gets its `stack` string when it is **constructed**, not when it is thrown or logged. Node's errors documentation states the limit precisely: the number of frames captured is bounded by **the smaller of `Error.stackTraceLimit` or the number of frames available on the current event loop tick**. That second clause is the whole story for callback code. Node runs your JavaScript in **ticks**: the event loop picks up a completed timer, socket read or file operation, calls its callback, and the stack starts again from that callback. The function that issued the original request returned long ago, so its frame is no longer on any stack. ## Why an await chain still shows your callers An `async` function suspended at `await` is not on the call stack either, but V8 keeps enough information to reconstruct it. When an error is created in an async function that has resumed after an `await`, V8 walks the chain of async functions that are awaiting the current one and appends them to the trace as async frames. So a failure in `repo.findOrder()`, awaited by `service.getOrder()`, awaited by the route handler, still names all three. This reconstruction only works while every link is an `await` on a promise. It cannot cross: - a **callback** invoked later by a driver, timer or event emitter; - a **`.then()` callback** chain where no async function is awaiting; - a link where the promise was created and handed off rather than awaited. The JavaScript lessons on async functions cover the language side of this; what matters for a Node service is where its libraries break the chain. ## The driver case, step by step 1. Your handler calls `db.query(sql, (err, rows) => ...)`, and the driver writes to a socket and returns. 2. Later, libuv reports the socket readable; the driver parses a failure and creates `new Error('connection reset')` inside its own parsing function. 3. That `Error` captures the current tick: the driver's socket-data handler and parser. Your handler is not on the stack and no `await` links to it. ## What actually helps | Technique | What it fixes | Cost or caveat | |---|---|---| | `util.promisify` the driver and `await` it | your async callers reappear on errors you create after the `await` | needs a callback with the standard error-first signature | | Wrap at the boundary: `throw new Error('order lookup failed', { cause: err })` | the new error is created in your async function, so it carries your await chain | the driver's own frames move to `cause` | | `Error.stackTraceLimit = 50` or `--stack-trace-limit=50` | traces cut at the default **10** frames before reaching your code | every captured stack gets bigger | | `--enable-source-maps` | frames point at original TypeScript or bundled sources | overriding `Error.prepareStackTrace` can stop it unless you call the original | | `AsyncLocalStorage` request id | identifies the request even when the stack cannot | the id still has to be logged with the error | `Error.stackTraceLimit` applies to stacks captured **after** it is changed, and the documentation notes that a non-number or negative value captures no frames at all. Deep framework middleware easily consumes ten frames, so a trace that "stops" just before your code may be truncation rather than a broken async chain: count the frames before blaming the driver. ## Reading the result - If the trace has exactly ten frames and ends mid-framework, raise the limit. - If it ends at a socket or parser function with no caller of yours, the chain broke at a callback: promisify and wrap. - If file names are compiled output, turn on source maps. ## When the stack cannot help Some failures will never carry your callers: an error emitted by a long-lived socket, a pool's background health check, a timer the library owns. For those, the stack answers "where in the driver" and something else must answer "which request". That is the job of a request id carried in `AsyncLocalStorage` and written next to the error at the point it is logged, so a trace with only driver frames still lines up with the request that was waiting on it. None of these makes stacks free: a larger limit means more work for every error constructed, which matters in code that creates errors on hot paths. Keep the limit moderate and set it once at start-up, in `NODE_OPTIONS` or the entry file, rather than toggling it per request.
- What is the default `Error.stackTraceLimit` in Node.js, and how do you change it?It is 10. Set `Error.stackTraceLimit = 30` in code, which affects stacks captured after the assignment, or start Node with `--stack-trace-limit=30`, which can also go in `NODE_OPTIONS`. Setting it to 0 disables stack collection, and a negative or non-number value captures no frames.
- Why does rethrowing the driver's failure as a new `Error` inside your async function give a more useful stack?The new error is constructed after your function has resumed from `await`, so its stack starts in your code and V8 can append the async functions awaiting it, up to the route handler. The driver's original error, kept on `cause`, still holds the low-level frames. One error tells you which request path failed, the other where in the driver.
- Saying a stack trace is captured when the error is thrown
- Claiming V8 links a callback's stack back to the code that registered it
- Assuming every truncated trace is a broken async chain
- Raising Error.stackTraceLimit as if larger stacks were free
- Expecting .then() callbacks to show the async callers like await does