Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show only my lines of code in error stack trace in NodeJS?

Is there a way to filter out the lines of code from error stack trace that I can't control or debug? I mean, my nodeJS project depends on many third party dependencies and I don't pretend to debug them. It just ads noise to the stack trace.

For example, here I just want to show lines 1 and 7, because the file prepareServer.js is the one I created, all the others are not mine.

Error
    at buildAdministrationsObject (/home/joao/dev/geoptapi/prepareServer.js:350:11)
    at /home/joao/dev/geoptapi/node_modules/async/dist/async.js:3638:28
    at replenish (/home/joao/dev/geoptapi/node_modules/async/dist/async.js:443:21)
    at iterateeCallback (/home/joao/dev/geoptapi/node_modules/async/dist/async.js:427:21)
    at /home/joao/dev/geoptapi/node_modules/async/dist/async.js:324:20
    at /home/joao/dev/geoptapi/node_modules/async/dist/async.js:3643:17
    at /home/joao/dev/geoptapi/prepareServer.js:158:7
    at wrapper (/home/joao/dev/geoptapi/node_modules/async/dist/async.js:271:20)
    at iterateeCallback (/home/joao/dev/geoptapi/node_modules/async/dist/async.js:424:28)
    at /home/joao/dev/geoptapi/node_modules/async/dist/async.js:324:20

Basically I just want to show in the stack files within my project and exclude files in node_modules/

like image 233
João Pimentel Ferreira Avatar asked Apr 26 '26 13:04

João Pimentel Ferreira


1 Answers

Came up with this solution that strips out any line with /node_modules/ or \node_modules\

const stripedStack = (new Error().stack).replace(/^.*[\\/]node_modules[\\/].*$/gm, '').replace(/\n+/g, '\n')
console.error(stripedStack)

Now as I wanted :)

Error
    at readShapefile (/home/joao/dev/geoptapi/prepareServer.js:106:16)
    at /home/joao/dev/geoptapi/prepareServer.js:100:7

Use for example like this with try/catch

try {
  // some code to run
} catch (err) {
  console.error(parseErr(err))
}

function parseErr(err) {
  return ((new Error(err).stack).replace(/^.*[\\/]node_modules[\\/].*$/gm, '').replace(/\n+/g, '\n'))
}
like image 161
João Pimentel Ferreira Avatar answered May 05 '26 10:05

João Pimentel Ferreira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!