如何在不使用console.log的情况下访问与console.log(Error('example'))相同的功能

时间:2019-11-24 06:15:39

标签: javascript node.js

示例:

> console.log(Error('test'))
Error: test
    at repl:1:13
    at Script.runInThisContext (vm.js:116:20)
    at REPLServer.defaultEval (repl.js:404:29)
    at bound (domain.js:420:14)
    at REPLServer.runBound [as eval] (domain.js:433:12)
    at REPLServer.onLine (repl.js:715:10)
    at REPLServer.emit (events.js:215:7)
    at REPLServer.EventEmitter.emit (domain.js:476:20)
    at REPLServer.Interface._onLine (readline.js:316:10)
    at REPLServer.Interface._line (readline.js:693:8)

我想将整个字符串与堆栈一起存储为字符串。但这不起作用,它没有堆栈。如何访问相同的功能?

> e = Error('test')
> console.log(e.toString())
Error: test
> console.log('' + e)
Error: test

1 个答案:

答案 0 :(得分:2)

您必须访问错误实例的stack属性:

const foo = () => {
  bar();
};
const bar = () => {
  const error = new Error('some error');
  console.log(error.stack);
};

foo();