javascript node.js getting line number in try catch?

妖精的绣舞 提交于 2019-12-20 10:02:21

问题


I'm using try catch on a node.js script:

try {} catch (err) {console.log(err)}

I get an output like this:

{ stack: [Getter/Setter],
  arguments: [ 'undefined' ],
  type: 'called_non_callable',
  message: [Getter/Setter] }

Is there an easy way to make this more informative? Include line numbers and function names and such?


回答1:


Those [Getter/Setter] members indicate further information available on the error object. You can easily dump the contents of those getters/setters using a small helper function (very trivial implementation, further refinement is up to you)

function dumpError(err) {
  if (typeof err === 'object') {
    if (err.message) {
      console.log('\nMessage: ' + err.message)
    }
    if (err.stack) {
      console.log('\nStacktrace:')
      console.log('====================')
      console.log(err.stack);
    }
  } else {
    console.log('dumpError :: argument is not an object');
  }
}

try {
  not_defined.function_call();
} catch(err) {
  dumpError(err);
}

You could also extend the Object.prototype for improved accessability (so you could use err.dumpError()), although extending Object.prototype bears the risk of overwriting existing functionality.



来源:https://stackoverflow.com/questions/5802840/javascript-node-js-getting-line-number-in-try-catch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!