dman
dman

Reputation: 11064

Getting filename in line number in trace stack/Error object

I'm improving my error handling in Node.js/express.

Is there a way to get the filename and line number where this error occurred in my code?

error-handler.js, using console.trace, is only the route that handles errors...not where the error actually happened at.


class FacebookErr extends Error {
  constructor(httpCode, ...args) {
    super(...args)
    Error.captureStackTrace(this, FacebookErr);
    this.name = 'FacebookErr';
    this.date = new Date();
    this.httpCode = httpCode;
  }
}

  fetch(uri)
    .then(status)
    .then(toJson)
    .then(getUserInfo)
    .catch((err) => {
      next(new FacebookErr(500, err));
    });

Trace: FacebookErr: ReferenceError: uri is not defined
    at log (/home/one/github/dolphin/app/error-handler.js:4:11)
    at Layer.handle_error (/home/one/github/dolphin/node_modules/express/lib/router/layer.js:71:5)
    at trim_prefix (/home/one/github/dolphin/node_modules/express/lib/router/index.js:315:13)
    at /home/one/github/dolphin/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/one/github/dolphin/node_modules/express/lib/router/index.js:335:12)
    at Immediate.next (/home/one/github/dolphin/node_modules/express/lib/router/index.js:275:10)
    at Immediate.<anonymous> (/home/one/github/dolphin/node_modules/express/lib/router/index.js:635:15)
    at runCallback (timers.js:783:20)
    at tryOnImmediate (timers.js:743:5)
    at processImmediate [as _immediateCallback] (timers.js:714:5)
Sun Dec 24 2017 13:39:37 GMT-0600 (CST)

Upvotes: 1

Views: 2140

Answers (1)

lkm
lkm

Reputation: 621

Using regex... the following will give you the the filename (full path), line number and column number of the first file in the stack trace:

const [, filename, line, column ] = err.stack.match(/\/([\/\w-_\.]+\.js):(\d*):(\d*)/)

If you want to get info for the first file in your project, not one in node_modules:

const regEx =  = new RegExp(`${process.cwd()}\\/(?!node_modules\\/)([\\/\\w-_\\.]+\\.js):(\\d*):(\\d*)`)
const [, filename, line, column ] = err.stack.match(regEx)

Upvotes: 3

Related Questions