javascript / expert
Snippet
Structured Stack Trace Customization
V8 provides a non-standard API to customize stack traces. By overriding 'Error.prepareStackTrace', you can intercept the array of CallSite objects, allowing you to format logs as structured JSON or perform advanced error analysis instead of parsing raw strings.
snippet.js
1
2
3
4
5
6
7
8
9
10
Error.prepareStackTrace = (err, stack) => {return stack.map(frame => ({function: frame.getFunctionName(),file: frame.getFileName(),line: frame.getLineNumber()}));};const getTrace = () => new Error().stack;console.log(getTrace());
nodejs
Breakdown
1
Error.prepareStackTrace = (err, stack) => {
Global override that defines how stack traces are formatted for all errors.
2
frame.getFunctionName(),
Accesses the name of the function where the error or trace occurred.
3
return stack.map(frame => ({ ... }));
Converts raw V8 CallSite objects into a clean, serializable JavaScript array.
4
const getTrace = () => new Error().stack;
Accessing '.stack' triggers the custom formatter defined above.