【问题标题】:Can't catch error in nodejs and mongodb无法在 nodejs 和 mongodb 中捕获错误
【发布时间】:2015-12-02 00:59:55
【问题描述】:

我有一些类似打击的代码, 如果抛出 1,则显示为

catch in main
throw 1

如果抛出2,显示将是

catch in test
throw 2

但如果我想这样显示,

catch in test
throw 2
catch in main
throw 2 

我该怎么办?

function test(database)
{
  if(1) throw 'throw 1';   //if throw at here, 'catch in main' will display
  var col=database.collection('profiles');
  col.findOne({"oo" : 'xx'})
  .then(function(doc){
      throw 'throw 2';  //if throw at here, 'catch in main' will [NOT] display
  })
  .catch(function(e){
    console.log('catch in test');
    console.log(e);
    throw e;
  });
}

MongoClient.connect(url, function(err, database) {
  try{
    test(database);
  }catch(e){
    console.log('catch in main');  //if throw 2, this line will [NOT] run
    console.log(e);
  }
});

【问题讨论】:

    标签: node.js mongodb try-catch throw


    【解决方案1】:

    当您使用 Promise 时(在这种情况下就是您),几乎没有使用将客户端代码包装在 try-catch 中的情况。你应该做的是 1) 从test 函数返回一个承诺; 2) 使用catch 方法订阅返回的promise'reject。一种可能的方法:

    // in test()
    return col.findOne({"oo" : 'xx'})
    .then(function(doc){
      throw 'throw 2';  //if throw at here, 'catch in main' will [NOT] display
    })
    .catch(function(e){
      console.log('catch in test');
      console.log(e);
      throw e; // 
    });
    
    // in main:
    function handleError(e) {
      console.log('catch in main');
      console.log(e);
    }
    
    // ...
    try {
      test(database).catch(handleError);
    } catch(e) {
      handleError(e);
    }
    

    顺便说一句,在我看来,您的第一个示例(使用您自己的代码)是人为的(引入只是为了确保 try-catch 在一般情况下有效),而在您的实际情况下,只有 DB 函数可能会结束有错误。如果我是正确的,您可能希望完全摆脱 try-catch 块:承诺 .catch 处理程序就足够了。

    【讨论】:

      猜你喜欢
      • 2020-04-06
      • 2021-02-25
      • 1970-01-01
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      相关资源
      最近更新 更多