0

This connect expected to error but I should able to caught promise rejections. But the results that I get said unhandled promise rejection. ( I got double mongoError from console.log() as expected ) Thank you for your suggestion and advice.

mongodbModule.js file

var connection;
module.exports.mongodbConnect = () => {
    return new Promise(async (resolve, reject) => {
        if (!connection) {
            try {
                connection = await mongoClient.connect(uri, opts);
                let database = connection.db(dbName);
                resolve(database)
            } catch (mongoErr) {
                console.log(mongoErr);
                reject(mongoErr);
            }
        }
    });
};

app.js

const mongoConnect = require('./modules/mongodbModule').mongodbConnect;
const connectDb = () => {
    return new Promise( async (resolve,reject) => {
        try {
            let db = await mongoConnect()
            resolve(db);
        } catch (err) {
            reject(err);
        }
    });
};

connectDb()
    .then((db) => {
        console.log(db)
    })
    .catch((mongoErr) => {
        console.log(mongoErr)
        throw mongoErr;
    });

error

(node:26864) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
(node:26864) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Nrto
  • 43
  • 6
  • Problem is throw after catch. More info : https://stackoverflow.com/questions/45771024/how-to-properly-throw-an-error-if-promise-is-rejected-unhandledpromiserejectio – Nrto May 24 '18 at 01:46

1 Answers1

1

You should not throw the error inside the catch.

.catch(e => {
    console.log(e);
    process.exit(1); // to exit with no error use 0
 });

A thrown error in Express.js will shut down your application.

desoares
  • 861
  • 7
  • 15
  • I expected this to shut down my application in case of error ( This isn't webservice ). But the problem really is throw though. Thanks for your suggestion ! – Nrto May 24 '18 at 01:46