javascript / expert
Snippet
Custom Stack Trace Reformatting via Error.prepareStackTrace Introspection
V8 allows overriding Error.prepareStackTrace to gain access to structured CallSite objects rather than plain string stack traces. This enables programmatically auditing file paths, line numbers, function names, and native execution frames for security monitoring or advanced diagnostics.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function captureCallsiteAudit() {const originalPrepare = Error.prepareStackTrace;Error.prepareStackTrace = (_, stack) => {return stack.map((site) => ({file: site.getFileName(),line: site.getLineNumber(),fn: site.getFunctionName() || '<anonymous>',isNative: site.isNative()}));};const err = new Error();Error.captureStackTrace(err, captureCallsiteAudit);const stackFrames = err.stack;Error.prepareStackTrace = originalPrepare;return stackFrames;}const auditLog = captureCallsiteAudit();
nodejs
Breakdown
1
Error.prepareStackTrace = (_, stack) => {
Overrides V8's stack formatting hook to intercept structured CallSite objects.
2
file: site.getFileName(), line: site.getLineNumber(),
Extracts exact callsite file location and execution line number from the CallSite API.
3
Error.captureStackTrace(err, captureCallsiteAudit);
Omits frames above the specified target function to slice off internal diagnostic boilerplate.
4
Error.prepareStackTrace = originalPrepare;
Restores the original stack trace formatter to avoid leakages or side-effects in global error handling.