Reputation: 1432
I am new to mongoose.I am using Sails js, Mongo DB and Mongoose in my project. My basic requirement was to find details of all the users from my user
collection. My code is as follows:
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
}
Here user
is a model which contains all the user
details. I had sails lifted my app and then I closed my MongoDB
connection. I ran the API
on DHC
and found the following:
API
for the first time on DHC
, the API
took more than 30 sec to show me an error that the MongoDB
connection is not avaliable.API
for the second time, The API
timed out without giving an response.My Question here why is the try
and catch
block unable to handle such an error exception effectively in mongoose
or is it something that I am doing wrong?
EDIT My Requirement is that mongoose should display the error immediately if the DB connection is not present.
Upvotes: 6
Views: 5593
Reputation: 3114
First let’s take a look at a function that uses a synchronous usage pattern.
// Synchronous usage example
var result = syncFn({ num: 1 });
// do the next thing
When the function syncFn
is executed the function executes in sequence until the function
returns and you’re free to do the next thing. In reality, synchronous functions should be
wrapped in a try/catch. For example the code above should be written like this:
// Synchronous usage example
var result;
try {
result = syncFn({ num: 1 });
// it worked
// do the next thing
} catch (e) {
// it failed
}
Now let’s take a look at an asynchronous function usage pattern.
// Asynchronous usage example
asyncFn({ num: 1 }, function (err, result) {
if (err) {
// it failed
return;
}
// it worked
// do the next thing
});
When we execute asyncFn
we pass it two arguments. The first argument is the criteria to be used by the function. The second argument is a callback that will execute whenever asyncFn
calls the callback. asyncFn
will insert two arguments in the callback – err
and result
). We
can use the two arguments to handle errors and do stuff with the result.
The distinction here is that with the asynchronous pattern we do the next thing within the callback of the asynchronous function. And really that’s it.
Upvotes: 5