I realize this may seem like a duplicate of other questions, but I have looked at every suggested SO question I could find before posting this, and I am looking for help on this specific scenario, as none of the other answers have worked for me.
I have a Node/Express app that is initializing a single MongoDB connection to be used by a REST API. The first step is to connect to the MongoDB instance. If the initial connection fails, it will throw an error as expected. I am using async/await with a try/catch block inside of it to handle that. Everywhere I have looked says that this should be sufficient to catch these async/await promise rejections, but I keep getting an error about an UnhandledPromiseRejection no matter where I throw in a .catch()
or try/catch for my code (as suggested in other SO posts).
In this link, for instance, I have pretty much the same thing that is described in the error handling section, but the problem still exists.
https://javascript.info/async-await
Here's the error (I know what is causing the error itself - I have the MongoDB service stopped right now - but I am trying to fix the unhandled promise rejection error):
(node:15633) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:15633) [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.
(node:13802) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
at Pool.<anonymous> (/home/allen/scripts/lysi/eosMain/node_modules/mongodb-core/lib/topologies/server.js:562:11)
at Pool.emit (events.js:189:13)
at Connection.<anonymous> (/home/allen/scripts/lysi/eosMain/node_modules/mongodb-core/lib/connection/pool.js:316:12)
at Object.onceWrapper (events.js:277:13)
at Connection.emit (events.js:189:13)
at Socket.<anonymous> (/home/allen/scripts/lysi/eosMain/node_modules/mongodb-core/lib/connection/connection.js:245:50)
at Object.onceWrapper (events.js:277:13)
at Socket.emit (events.js:189:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
and here's my code:
exports.mongoConnect = async (dbName, archiveDbName, userName, password) => {
// Auth params
const user = encodeURIComponent(userName);
const pass = encodeURIComponent(password);
const authMechanism = 'DEFAULT';
// Connection URL
const url = `mongodb://${user}:${pass}@localhost:27017?authMechanism=${authMechanism}&authSource=admin`;
let client;
try {
// Use connect method to connect to the Server
client = await MongoClient.connect(url, { useNewUrlParser: true, poolSize: 10, autoReconnect: true, reconnectTries: 6, reconnectInterval: 10000 }).catch((e) => { console.error(e) });
db = client.db(dbName);
archiveDb = client.db(archiveDbName);
console.log(`Succesfully connected to the MongoDb instance at URL: mongodb://localhost:27017/ with username: "` + client.s.options.user + `"`);
console.log(`Succesfully created a MongoDb database instance for database: "` + db.databaseName + `" at URL: mongodb://localhost:27017/`);
console.log(`Succesfully created a MongoDb database instance for database: "` + archiveDb.databaseName + `" at URL: mongodb://localhost:27017/`);
} catch (err) {
console.log(`Error connecting to the MongoDb database at URL: mongodb://localhost:27017/` + dbName);
}
}
that is being called from app.js like this:
mongoUtil.mongoConnect('myDb', 'myArchiveDb', 'myUser', 'myPassword');
I even tried putting that line in a try/catch block, or adding the promise-style .catch()
onto the end of it, with no change.
I can't seem to figure out why it's still complaining about not handling the promise rejection.
EDIT:
Here's the whole app.js file:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var app = express();
const MongoClient = require('mongodb').MongoClient;
// This is where the mongo connection happens
var mongoUtil = require( './services/mongoUtil' );
var bluebird = require('bluebird');
const jwt = require('./helpers/jwt');
var api = require('./routes/api.route')
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api', api);
// use JWT auth to secure the api
app.use(jwt());
app.use('/users', require('./users/users.controller'));
MongoClient.Promise = bluebird
mongoUtil.mongoConnect('myDb', 'myArchiveDb', 'username', 'password');
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;`
Promise
notation?MongoClient.connect(...).then(() => { // all good }).catch((error) => { // error here })
- molamkMongoClient.connect
even return a Promise? - Rashomon