lib: stop using prepareStackTrace by devsnek · Pull Request #29777 · nodejs/node · GitHub
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions lib/assert.js
19 changes: 17 additions & 2 deletions lib/internal/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,18 @@ const { kMaxLength } = internalBinding('buffer');

const MainContextError = Error;
const ErrorToString = Error.prototype.toString;
// Polyfill of V8's Error.prepareStackTrace API.
// https://crbug.com/v8/7848
const overrideStackTrace = new WeakMap();
const prepareStackTrace = (globalThis, error, trace) => {
// API for node internals to override error stack formatting
// without interfering with userland code.
if (overrideStackTrace.has(error)) {
const f = overrideStackTrace.get(error);
overrideStackTrace.delete(error);
return f(error, trace);
}

// Polyfill of V8's Error.prepareStackTrace API.
// https://crbug.com/v8/7848
// `globalThis` is the global that contains the constructor which
// created `error`.
if (typeof globalThis.Error.prepareStackTrace === 'function') {
Expand All @@ -36,6 +45,11 @@ const prepareStackTrace = (globalThis, error, trace) => {
return MainContextError.prepareStackTrace(error, trace);
}

// Normal error formatting:
//
// Error: Message
// at function (file)
// at file
const errorString = ErrorToString.call(error);
if (trace.length === 0) {
return errorString;
Expand Down Expand Up @@ -680,6 +694,7 @@ module.exports = {
// This is exported only to facilitate testing.
E,
prepareStackTrace,
overrideStackTrace,
kEnhanceStackBeforeInspector,
fatalExceptionStackEnhancers
};
Expand Down
13 changes: 6 additions & 7 deletions lib/internal/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ const {
ERR_NO_CRYPTO,
ERR_UNKNOWN_SIGNAL
},
uvErrmapGet
uvErrmapGet,
overrideStackTrace,
} = require('internal/errors');
const { signals } = internalBinding('constants').os;
const {
Expand Down Expand Up @@ -338,15 +339,13 @@ function isInsideNodeModules() {
// side-effect-free. Since this is currently only used for a deprecated API,
// the perf implications should be okay.
getStructuredStack = runInNewContext(`(function() {
Error.prepareStackTrace = function(err, trace) {
return trace;
};
Error.stackTraceLimit = Infinity;

return function structuredStack() {
return new Error().stack;
const e = new Error();
overrideStackTrace.set(e, (err, trace) => trace);
return e.stack;
};
})()`, {}, { filename: 'structured-stack' });
})()`, { overrideStackTrace }, { filename: 'structured-stack' });
}

const stack = getStructuredStack();
Expand Down
64 changes: 31 additions & 33 deletions lib/repl.js