Node.js: Visual code snippets and cleaner stack traces with your Node.js code
Last updated: 28th April 2017Use the callsite-record package on NPM to create pretty looking stack traces. To give an example, if I throw an error in my Node.js Express route handler, I see a stack trace like this:
Error: Average Stack Traces
at someAsyncThing (/Users/uhn7899/development/modern-devtools/src/server/routes/index.js:25:8)
at router.get (/Users/uhn7899/development/modern-devtools/src/server/routes/index.js:29:8)
at Layer.handle [as handle_request] (/Users/uhn7899/development/modern-devtools/node_modules/express/lib/router/layer.js:95:5)
at Layer.handle [as handle_request] (/Users/uhn7899/development/modern-devtools/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/uhn7899/development/modern-devtools/node_modules/express/lib/router/index.js:317:13)
...
Many others lines
...
at next (/Users/uhn7899/development/modern-devtools/node_modules/express/lib/router/index.js:275:10)
This stack trace has a lot of noise and contains information I'm not interested in.
To improve this, I can create a cleaner stack trace function:
function cleanStackTrace(reason) {
return require('callsite-record')({
forError: reason
}).renderSync({
stackFilter(frame) {
return !frame.getFileName().includes('node_modules');
}
});
}
And use it like this:
process.on('unhandledRejection', reason => {
console.log(cleanStackTrace(reason));
});
Because I am excluding code in node_modules, my stack trace now looks like this, in its entirety:
at someAsyncThing (/Users/uhn7899/development/modern-devtools/src/server/routes/index.js:23:8)
at router.get (/Users/uhn7899/development/modern-devtools/src/server/routes/index.js:27:8)
And I see the exact snippet of code, with syntax highlighting, which caused the error. I can see this snippet without going back to my editor:
21 |
22 |async function someAsyncThing() {
> 23 | throw new Error('Better Stack Traces');
24 |}
25 |
Notes:
- Consider your project carefully, you may not wish to hide code present in
node_modules
. - This example hooks into
unhandledRejection
, but it is generally safer to handle your errors earlier on.