我正在 try catch 可能在异步函数中引发的错误。
我尝试使用 Fiber 包,但安装此包后,应用程序不会开始出现此错误:
=> Errors prevented startup:
While building the application:
node_modules/fibers/build.js:1:15: Unexpected token ILLEGAL
所以我放弃了这个包(这也意味着 Future
类)...
我还尝试使用 Meteor.wrapAsync
包装回调函数,但这也不起作用。
这是我正在使用的代码:
try {
Meteor.users.update({
_id: this.user_id
},{
$set: {first_name: "test"}
},{
multi: false
}, function(error, response){
if(response < 1)
throw "user could not be updated!";
});
console.log('user updated');
}
catch(error) {
console.log('catched');
console.error(error);
}
由于回调函数是异步的,因此它不会被捕获,因为抛出错误时 catch block 代码已经运行。我只是想找出一种方法来捕获我抛出的错误。
最佳答案
在服务器上,collection.update
已经可以同步使用。所以你需要做的就是:
try {
var documentsAffected = Meteor.users.update({
_id: this.user_id
},{
$set: {first_name: "test"}
},{
multi: false
});
if (documentsAffected < 1) {
throw new Error("user could not be updated!");
}
console.log("user updated");
} catch (error) {
// will also catch exceptions thrown by Meteor.users.update
console.log("caught an error!");
console.error(error);
}
关于javascript - Meteor:如何捕获异步回调函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26232757/