shu*_*l92 5 try-catch mongoose mongodb node.js sails.js
我是mongoose的新手,我在项目中使用Sails js,Mongo DB和Mongoose。我的基本要求是从我的user 收藏中查找所有用户的详细信息。我的代码如下:
try{
user.find().exec(function(err,userData){
if(err){
//Capture the error in JSON format
}else{
// Return users in JSON format
}
});
}
catch(err){
// Error Handling
}
Run Code Online (Sandbox Code Playgroud)
这user是一个包含所有细节的模型user。我扬帆起航,解除了我的应用程序,然后关闭了MongoDB连接。我继续API进行DHC,发现以下内容:
API在第一时间DHC,在API花了超过30秒,告诉我一个错误的MongoDB 连接是暂无数据。API了第二个时,API不会给响应超时。我的问题在这里,为什么 try and catch块无法有效地处理这样的错误 异常,mongoose或者我做错了什么?
编辑 我的要求是,如果数据库连接不存在,猫鼬应立即显示错误。
首先让我们看一下使用同步使用模式的函数。
// Synchronous usage example
var result = syncFn({ num: 1 });
// do the next thing
Run Code Online (Sandbox Code Playgroud)
当函数syncFn被执行时,函数会按顺序执行,直到函数返回并且你可以自由地做下一件事情。实际上,同步函数应该包含在 try/catch 中。例如上面的代码应该这样写:
// Synchronous usage example
var result;
try {
result = syncFn({ num: 1 });
// it worked
// do the next thing
} catch (e) {
// it failed
}
Run Code Online (Sandbox Code Playgroud)
现在让我们看一下异步函数的使用模式。
// Asynchronous usage example
asyncFn({ num: 1 }, function (err, result) {
if (err) {
// it failed
return;
}
// it worked
// do the next thing
});
Run Code Online (Sandbox Code Playgroud)
当我们执行时,asyncFn我们传递了两个参数。第一个参数是函数使用的条件。第二个参数是一个回调,每当asyncFn调用回调时都会执行。asyncFn将在回调中插入两个参数 -err和result)。我们可以使用这两个参数来处理错误并对结果进行处理。
这里的区别在于,使用异步模式,我们在异步函数的回调中执行下一步操作。真的就是这样。
| 归档时间: |
|
| 查看次数: |
2540 次 |
| 最近记录: |