question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Way to handle mongoose.connect() error in promise catch handler

See original GitHub issue

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);
    });

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:10
  • Comments:31 (6 by maintainers)

github_iconTop GitHub Comments

24reactions
mathieugcommented, May 10, 2016

Use the callback of mongoose.connect to catch any error during the connection. You can start you server in the event open.

        mongoose.connection.once('open', function() {
            logger.info('MongoDB event open');
            logger.debug('MongoDB connected [%s]', url);

            mongoose.connection.on('connected', function() {
                logger.info('MongoDB event connected');
            });

            mongoose.connection.on('disconnected', function() {
                logger.warn('MongoDB event disconnected');
            });

            mongoose.connection.on('reconnected', function() {
                logger.info('MongoDB event reconnected');
            });

            mongoose.connection.on('error', function(err) {
                logger.error('MongoDB event error: ' + err);
            });

            // return resolve();
            return server.start();
        });

        return mongoose.connect(url, options, function(err) {
            if (err) {
                logger.error('MongoDB connection error: ' + err);
                // return reject(err);
                process.exit(1);
            }
        });
21reactions
nasr18commented, May 10, 2016
mongoose.connect('mongodb://localhost/dbCollection', function(err, db) {
    if (err) {
        console.log('Unable to connect to the server. Please start the server. Error:', err);
    } else {
        console.log('Connected to Server successfully!');
    }
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

is there a mongoose connect error callback - Stack Overflow
The error comes from the Mongoose documentation for connect() mongoosejs.com/docs/connections.html, which does not specify a callback is possible. – mikemaccana.
Read more >
Mongoose v6.8.2: Connecting to MongoDB
There are two classes of errors that can occur with a Mongoose connection. ... To handle initial connection errors, you should use .catch()...
Read more >
Using Express.js Routes for Promise-based Error Handling
This Express.js tutorial shows you how to centralize Express.js error ... in every route and add them to each promise passed to then()...
Read more >
mongoose-validation-error-message-handler - npm
Mongoose Validation Error Message Handler. Latest version: 1.2.5, last published: 9 months ago.
Read more >
How to handle errors for async code in Node.js - GeeksforGeeks
When we are using the then() method to consume the promise and we have to handle the promise rejections, then we can a...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found