Skip to content

Instantly share code, notes, and snippets.

@pwfcurry
Created October 4, 2022 09:49
Show Gist options
  • Save pwfcurry/81ed1efb3184bd6916dfaec83326a4c5 to your computer and use it in GitHub Desktop.
Save pwfcurry/81ed1efb3184bd6916dfaec83326a4c5 to your computer and use it in GitHub Desktop.
Enhance async stack traces
// Async stack traces are often a bit useless - there is a max depth after which context is lost.
// This is a rather hacky attempt to maintain the full stack.
// https://github.com/sindresorhus/got/blob/main/documentation/async-stack-traces.md
// https://github.com/nodejs/node/issues/36126
const asyncHooks = require("async_hooks");
const traces = new Map();
asyncHooks
.createHook({
init(id) {
const trace = {};
Error.captureStackTrace(trace);
traces.set(id, trace.stack.replace(/(^.+$\n){4}/m, "\n"));
},
destroy(id) {
traces.delete(id);
},
})
.enable();
globalThis.Error = class extends Error {
constructor(message) {
super(message);
this.constructor.captureStackTrace(this, this.constructor);
}
static captureStackTrace(what, where) {
super.captureStackTrace.call(Error, what, where);
const trace = traces.get(asyncHooks.executionAsyncId());
if (trace) {
// remove noisy internals from the stack
const filteredTrace = trace
.split("\n")
.filter((line) => line.indexOf("node:internal") === -1 && line.indexOf("jest-circus") === -1)
.join("\n");
what.stack += filteredTrace;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment