javascript – 使用promise.catch和console.log的NodeJS错误?

前端之家收集整理的这篇文章主要介绍了javascript – 使用promise.catch和console.log的NodeJS错误?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

运行以下代码时,我会得到不同的结果,具体取决于我是否注释掉了console.log(“fnError:”,fnError).这对我来说似乎很不对劲.

世界上如何调用console.log影响我的承诺?

  1. function run() {
  2. var fn = function(){
  3. throw new Error("incorrect message");
  4. };
  5. // returns a promise that should fail with
  6. // an error object whose .message is "correct message"
  7. var promisifiedFn = function(){
  8. return Promise.resolve()
  9. .then(fn)
  10. .catch((fnError) => {
  11. // commenting this out fixes things! //
  12. console.log("fnError: ",fnError);
  13. ///////////////////////////////////////
  14. fnError.message = "correct message";
  15. throw fnError;
  16. })
  17. }
  18. promisifiedFn().catch((e) => {
  19. console.log("caught error.message:",e.message);
  20. console.log("caught error:",e);
  21. });
  22. }
  23. run();

以上产生:

  1. // fnError: Error: incorrect message
  2. // at fn (/Users/sam/dev/ethereum/pennyeth/js/temp.js:18:9)
  3. // at

注意记录“不正确的消息”.如果你注释掉console.log(“fnError:”,fnError),你会得到:

  1. // caught error.message: correct message
  2. // caught error: Error: correct message
  3. // at fn (/Users/sam/dev/ethereum/pennyeth/js/temp.js:18:9)
  4. // at

运行节点8.0.0

最佳答案
这是预期的行为.

记录错误(至少通过util.inspect或String)会评估其.stack属性.实例化错误对象时,不会初始化堆栈字符串,但是为了节省内存而延迟构建堆栈字符串.堆栈跟踪将包含错误消息,当您更改.message属性时,它将反映或不反映在堆栈跟踪中,具体取决于是否已创建.

the V8 stack trace API description开始:

For efficiency stack traces are not formatted when they are captured but on demand,the first time the stack property is accessed.

the official node Error documentation开始:

The string representing the stack trace is lazily generated when the error.stack property is accessed.

猜你在找的JavaScript相关文章