mongoose: Way to handle mongoose.connect() error in promise catch handler
How to handle mongoose.connect() error in catch handler? I want to use application initialization chain but can’t do that because mongoose.connect() does not return rejected promise. It returns rejected promise only if I specify callback, but it’s not a perfect solution.
Example:
mongoose.connect('mongodb://127.0.0.2/test') // if error it will throw async error
.then(() => { // if all is ok we will be here
return server.start();
})
.catch(err => { // we will not be here...
console.error('App starting error:', err.stack);
process.exit(1);
});
Workaround:
mongoose.connect('mongodb://127.0.0.2/test', function() { /* dummy function */ })
.then(() => {
return server.start();
})
.catch(err => { // mongoose connection error will be handled here
console.error('App starting error:', err.stack);
process.exit(1);
});
I think mongoose.connect() throws async error instead of return rejected promise in order to not break backward compatibility. Users expect that application will be finished with error code if something went wrong with mongoose connection establishment. If mongoose.connect() returns rejected promise application will be finished with 0 code and nothing will be output to console. So it will be good to have some way to say mongoose.connect() to return promise. Maybe something like exec():
mongoose.connect('mongodb://127.0.0.2/test').exec()
.then(() => { // if all is ok we will be here
return server.start();
})
.catch(err => { // if error we will be here
console.error('App starting error:', err.stack);
process.exit(1);
});
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 10
- Comments: 31 (6 by maintainers)
Use the callback of mongoose.connect to catch any error during the connection. You can start you server in the event open.
Just to confirm for anyone coming later, this works as expected:
I have the same issue as @matheo. Just opened this ticket:
https://github.com/christkv/mongodb-core/issues/163
That’s why I created this issue 😃
Why? No difference at all. When connection is opened,
mongoose.connectcallback will be called as well as returned promise will be fulfilled andopenevent will be emitted. So you can use what you wantI have the same issue.
I’d like to be able to use
mongoose.connect(...).catch(failCallback)but when an error occurs upon initial connection attemptfailCallbackdoes not execute. There’s something wrong with theMongooseThenablepseudo-promise thatmongoose.connectreturns. Moreover I have configuredmongoose.Promise = require('bluebird')and I really expect such async calls to return a real promise, a Bluebird one in my case.The problem with my
failCallbacknot executing, however, happens only initially, i.e.:But indeed it works like that (which is nonsensical):
Why is that?
@Jokero sorry dude… misunderstood your question. 😃
@nasr18 What did you mean? 😃 I don’t want to use callback)