javascript / expert
Snippet
Custom CallSite Inspection with V8 Error.prepareStackTrace
V8 allows customizing stack trace generation via Error.prepareStackTrace. By overriding this property, the stack property returns structured CallSite objects instead of a formatted string, enabling programmatically tracing call sites, file names, and line numbers.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
function getCallerLocation() {const original = Error.prepareStackTrace;Error.prepareStackTrace = (err, stack) => stack;const err = new Error();Error.captureStackTrace(err, getCallerLocation);const stack = err.stack;Error.prepareStackTrace = original;return {file: stack[0].getFileName(),line: stack[0].getLineNumber(),func: stack[0].getFunctionName() || 'anonymous'};}
nodejs
Breakdown
1
const original = Error.prepareStackTrace;
Saves the default stack trace formatter so it can be restored later.
2
Error.prepareStackTrace = (err, stack) => stack;
Replaces default formatting with a function that returns raw CallSite objects.
3
Error.captureStackTrace(err, getCallerLocation);
Captures the stack trace while omitting frames up to getCallerLocation.
4
Error.prepareStackTrace = original;
Restores the original prepareStackTrace handler to prevent global side effects.
5
file: stack[0].getFileName()
Accesses the CallSite API methods to extract caller file name and line metadata.