gpt4 book ai didi

node.js - 无法捕获nodejs和mongodb中的错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:22:35 24 4
gpt4 key购买 nike

我有一些代码,比如blow,如果抛出 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);
}
});

最佳答案

当您使用 Promise 时(在本例中),将客户端代码包装在 try-catch 中几乎没有什么用处。你应该做的是 1) 从 test 函数返回一个 promise ; 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 在一般情况下有效),在你的实际情况下,只有数据库函数可能会以错误结束。如果我是正确的,您可能希望完全摆脱该 try-catch block :promise .catch 处理程序就足够了。

关于node.js - 无法捕获nodejs和mongodb中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32422272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com