Detecting Mongoose/MongoDB error in Express route instead of Mongoose.connect callback Detecting Mongoose/MongoDB error in Express route instead of Mongoose.connect callback mongodb mongodb

Detecting Mongoose/MongoDB error in Express route instead of Mongoose.connect callback


This all turned out to be a red herring. The issue here was that there was an Express middleware layer that was making use of Mongo before the /healthcheck endpoint was reached.

In this case it was a Mongo session manager.

The solution was to exclude the /healthcheck URL from the session middleware.

function excludeSessionsForStaticURLs (req, res, next) {  if (!new RegExp(/\/about|\/api\/heartbeat|\/healthcheck|\.css|\.js|\.jpg|\.png'/)      .test(req.originalUrl)) {    return sessionMiddleware(req, res, next)  }  return next()}app.use(excludeSessionsForStaticURLs)

So now that this exclusion has been put in place, the normal try/catch (async/await) and .catch() for Promises works and the status for Mongo is reflected as False when appropriate.