Way to handle mongoose.connect() error in promise catch handler
See original GitHub issueHow 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);
});
Issue Analytics
- State:
- Created 7 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.