Sub topic 14
Stack Traces and Error.captureStackTrace
This chapter assumes you can write a custom error class that calls super(message, options) and sets this.name, as covered earlier. It also assumes you have run code in Node.js or a Chromium-based browser console.
What the stack property is
The stack property is a string. It describes where the error was created. No language specification defines it, but every major engine provides it. In V8, the engine behind Node.js and Chromium, it looks like this:
function parseAge(input) {
return new RangeError(`Invalid age: ${input}`);
}
const err = parseAge('abc');
console.log(err.stack);
// RangeError: Invalid age: abc
// at parseAge (file:///app/demo.js:2:10)
// at file:///app/demo.js:5:13
// ...The first line is the header, name: message. Each line after it is a stack frame: one function call that was active when the error was built.
When the stack is captured
The frames are recorded when the Error constructor runs. The throw statement does not record them. If you create an error in one place and throw it somewhere else, the trace points to where you created it.
V8 builds the header text lazily, when stack is first read. That is why setting this.name after super() still gives a header that starts with DatabaseError:. Other engines format stacks differently. Never parse stack in program logic. Only show it to humans or send it to logs.
Error.captureStackTrace
Error.captureStackTrace(target, constructorOpt) is a non-standard V8 API. It creates a fresh stack property on target. If you pass a function as constructorOpt, the trace leaves out that function and every frame above it. The trace then starts at that function's caller.
Modern V8 already hides the subclass constructor frames when you use new. So the most useful job for this API is hiding helper functions, such as error factories:
class DatabaseError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'DatabaseError';
}
}
function dbError(message, options) {
const err = new DatabaseError(message, options);
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(err, dbError);
}
return err;
}
function findUser(id) {
throw dbError(`Query for user ${id} failed`);
}
try {
findUser(7);
} catch (err) {
console.log(err.stack.split('\n')[1]);
// " at findUser (...)" rather than " at dbError (...)"
}Always guard the call with a feature check. Engines without the API will throw a TypeError if you call it unguarded.
Controlling trace length
V8 keeps 10 frames by default. Error.stackTraceLimit, which is also V8-only, changes that number for errors created after you set it:
Error.stackTraceLimit = 30;A higher limit helps when you are debugging deep async code. It also costs time and memory on every error you create, so keep the default in hot paths.
| Feature | Standard? | Where it works |
|---|---|---|
| `err.stack` | No, but universal | All major engines, with different formats |
| `Error.captureStackTrace` | No | V8 (Node.js, Chromium), plus some newer engines |
| `Error.stackTraceLimit` | No | V8 |
Exercise
A module creates const TIMEOUT = new Error('timeout') once at load time and throws it from several functions. Why are the stack traces from these throws misleading, and what is the fix?
Show answer
The stack is captured when the Error constructor runs, so every throw reports the module's load-time location, not the function that failed. Create a new error at each throw site, for example by calling a factory and passing it to Error.captureStackTrace.
Exercise
Why should captureStackTrace be wrapped in typeof Error.captureStackTrace === 'function'?
Show answer
It is a non-standard V8 API. In engines that lack it, the call would throw a TypeError inside your error constructor and hide the original failure.