Sub topic 14
Stack Traces and Error.captureStackTrace
This chapter assumes you can already write a custom error class with class ... extends Error, set its name, and pass options through to super. You should also be able to run snippets in Node.js, because most examples print V8-specific output. Node.js runs on V8, and so do Chrome and Edge.
A stack trace shows where an error came from. It is usually the first thing you read when something fails in production. Custom error classes change what ends up in that trace. This chapter explains when the trace is recorded, what it contains, and how to control it.
What the stack property is
stack is a string that holds the error's header line followed by a list of call frames. Here is a typical V8 trace:
function parseAge(input) {
const n = Number(input);
if (Number.isNaN(n)) {
throw new TypeError(`Not a number: ${input}`);
}
return n;
}
try {
parseAge('abc');
} catch (err) {
console.log(err.stack);
}
// TypeError: Not a number: abc
// at parseAge (/app/age.js:4:11)
// at Object.<anonymous> (/app/age.js:10:3)
// ...The ECMAScript specification does not define stack, but every major engine provides it. The format differs between engines:
| Engine | Used by | Frame format | Header line |
|---|---|---|---|
| V8 | Node.js, Chrome, Edge, Deno | ` at fn (file:line:col)` | `Name: message` |
| SpiderMonkey | Firefox | `fn@file:line:col` | none |
| JavaScriptCore | Safari, Bun | `fn@file:line:col` | none |
Write code that only displays or logs stack. Code that parses the string with regular expressions will break when it runs on a different engine.
When the trace is captured
An engine records the stack when the error object is created, not when it is thrown. This is easy to forget when errors are built in one place and thrown in another:
function makeError() {
return new Error('created here');
}
function fail() {
const err = makeError();
throw err; // the trace does not point at this line
}
try {
fail();
} catch (err) {
console.log(err.stack.split('\n')[1]);
// at makeError (/app/where.js:2:10)
}The same rule explains why rethrowing keeps the original trace. A bare throw err in a catch block does not record a new stack. The trace still points at the original failure, and that is usually what you want.
The header line and `name`
V8 builds the header line from the error's name and message, and it formats the string lazily, around the first time stack is read. A name you set inside the constructor therefore appears in the header, which is why ValidationError: Email is required shows up in Node output. If you change message or name after something has already read stack, the header will not update. Engines also differ on the exact timing, so set everything that belongs in the header inside the constructor.
Error.captureStackTrace
Error.captureStackTrace(target, constructorOpt) is a V8 API. It creates a stack property on target that holds the current call stack. If you pass constructorOpt, which is a function, V8 leaves out every frame above that function, including the function's own frame.
Other engines have begun to add this API, but it is not part of the language standard, so check that it exists before you call it. Here is the pattern from the topic plan:
class DatabaseError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'DatabaseError';
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, DatabaseError);
}
}
}
function query() {
throw new DatabaseError('Connection refused');
}
try {
query();
} catch (err) {
console.log(err.stack.split('\n').slice(0, 2).join('\n'));
// DatabaseError: Connection refused
// at query (/app/db.js:12:9)
}The goal is a trace whose first frame is the code that created the error. That frame should not be the constructor's own at new DatabaseError line.
Where it earns its keep: helper functions
The API matters most when a helper function creates the error for its caller. Assertion helpers and validation helpers are common examples. Without the call, every trace starts inside the helper, and that line tells you nothing:
class AssertionError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'AssertionError';
}
}
function assert(condition, message) {
if (!condition) {
const err = new AssertionError(message);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(err, assert);
}
throw err;
}
}
function withdraw(balance, amount) {
assert(amount <= balance, 'Insufficient funds');
return balance - amount;
}
try {
withdraw(10, 50);
} catch (err) {
console.log(err.stack.split('\n')[1]);
// at withdraw (/app/bank.js:19:3)
}Passing assert as constructorOpt drops the assert frame, so the first frame is the line in withdraw that broke the rule. Node's own assert module does the same thing.
Capturing a stack on a plain object
captureStackTrace works on any object, not only on errors. This can help with debugging, for example to record where a resource was opened so you can report a leak later:
function openHandle() {
const handle = { closed: false };
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(handle, openHandle);
}
return handle;
}
const h = openHandle();
console.log(typeof h.stack); // 'string'
console.log(h instanceof Error); // falseRelated V8 controls
| API | What it does | Default | Standard? |
|---|---|---|---|
| `Error.captureStackTrace(obj, fn)` | Adds a `stack` property to `obj` and hides frames above `fn` | n/a | No |
| `Error.stackTraceLimit` | Maximum number of frames to record | 10 | No |
| `Error.prepareStackTrace(err, frames)` | Hook that formats the stack from structured frame objects | unset | No |
| `node --stack-trace-limit=N` | Sets the frame limit from the command line | 10 | No (Node flag) |
The default limit of 10 frames often cuts off deep async or framework call stacks. You can raise it at startup:
Error.stackTraceLimit = 50;
function recurse(n) {
if (n === 0) throw new Error('bottom');
recurse(n - 1);
}
try {
recurse(30);
} catch (err) {
console.log(err.stack.split('\n').length - 1); // 32: 31 recurse frames plus the caller
}Gotchas and trade-offs
Capture cost
Recording a stack takes time. That cost hardly matters for real failures, but it adds up if you use errors for ordinary control flow in a hot loop, such as throwing an error to signal "not found" millions of times. In that case, return a value instead of throwing. Setting Error.stackTraceLimit = 0 globally is a bad trade, because you lose traces everywhere.
Async traces
V8 reconstructs async frames across await points, so a trace can show at async loadUser. It cannot do this for callbacks, timers, or plain .then chains outside async functions. When a trace ends at an event-loop boundary, the cause chain from earlier chapters is your best record of where the failure started.
The stack does not include the cause
err.stack describes only that one error. Node's util.inspect and its uncaught-exception output print [cause] blocks for you. Browsers and many loggers do not, so a wrapped error's trace can look like it began at the wrapper. The serialization chapter shows how to log both.
Do not expose stacks to clients
Stacks show file paths, dependency names, and code structure. Log them on the server, but leave them out of HTTP responses and user-facing messages.
Overwriting stack
stack is writable, and some libraries assign to it to merge traces. Avoid this in your own classes. A trace you edit by hand can point to code that never ran.
Summary
- The stack is captured when the constructor runs.
throwand rethrow keep it unchanged. - The
stackformat depends on the engine. Display it, but don't parse it. Error.captureStackTrace(target, fn)hides frames fromfnupward. Feature-detect it.- The biggest benefit comes in helper functions that create errors for their callers.
- Raise
Error.stackTraceLimitwhen deep traces get cut off.
Exercise
A function createError(code) builds and returns an AppError, and the code that calls it throws the result. Every logged trace starts with at createError. What change makes the first frame point at the code that called createError, and why does it work?
Show answer
Inside createError, after constructing the error, call Error.captureStackTrace(err, createError), guarded by a typeof Error.captureStackTrace === 'function' check. Passing createError as constructorOpt tells V8 to leave out that function's frame and everything above it, so the first frame becomes the caller's line.
Exercise
You create an error at module load (const TIMEOUT = new Error('timeout')) and throw that same object from several functions. Why are the stack traces misleading, and what should you do?
Show answer
The stack is recorded once, when the object is created at module load, so every throw shows the module-load frames and none of the real call sites. Create a new error at each throw site, for example throw new TimeoutError(), so that each trace reflects where the failure happened.
Exercise
Your Node service logs traces that stop after a few framework frames, so the application code is missing. Name a setting you could change, and give one reason not to set it to 0 to speed things up.
Show answer
Raise Error.stackTraceLimit, for example Error.stackTraceLimit = 50 at startup or node --stack-trace-limit=50. Setting it to 0 removes traces from every error in the process, including unexpected failures, and that makes production debugging much harder.