Search code examples
node.jsmongoosediscord.js

Why do I get 2 different outputs from the same Mongoose error?


I'm trying to handle an error from mongose by myself and from mongoose I get output:

MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://www.mongodb.com/docs/atlas/security-whitelist/

and this is from try catch block in connection.js:

try {
    await this.$initialConnection;
  } catch (err) {
    return await _handleConnectionErrors(err);
  }

In my file err.js I handle this with:

import chalk from 'chalk';

const name = 'error';
const invoke = async (err) => {
  console.log(chalk.rgb(255, 255, 255)('[Database error]: ' + `\n` + err));
};
export { invoke, name };

but output which I get is:

MongoServerSelectionError: connection <monitor> to 18.***.249.163:***** closed

Can anyone help me to handle this error to show in my own function as in Mongoose catch error block?


Solution

  • For me it is working now:

    import chalk from 'chalk';
    import ServerSelectionError from '../../../node_modules/mongoose/lib/error/serverSelection.js';
    const name = 'error';
    const invoke = async (err) => {
      if (err?.name === 'MongoServerSelectionError') {
        const originalError = err;
        err = new ServerSelectionError();
        err.assimilateError(originalError);
      }
      console.log(chalk.rgb(255, 0, 0)('[Database error]: ') + err);
      if ((err = 'MongooseServerSelectionError')) {
      }
    };
    export { invoke, name };