javascript node.js getting line number in try catch?

前端 未结 1 1398
日久生厌
日久生厌 2021-02-01 15:27

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

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

I get an output like this:

1条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-01 16:01

    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.

    0 讨论(0)
提交回复
热议问题