NodeJS 为什么我从同一个Mongoose错误中得到两个不同的输出?

l0oc07j2  于 2023-08-04  发布在  Node.js
关注(0)|答案(2)|浏览(88)

我试图自己处理mongose的错误,从mongoose得到输出:

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/

字符串
这是来自connection.js中的try catch块:

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


在我的err.js文件中,我用以下方式处理:

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


但我得到的输出是:

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


谁能帮我处理这个错误,在我自己的函数中显示为Mongoose catch错误块?

1rhkuytd

1rhkuytd1#

Mongoose连接可能出现两类错误。

1.初始连接错误:如果初始连接失败,Mongoose将发出一个'error'事件,并且mongoose.connect()返回的promise将拒绝。
1.但是,Mongoose不会自动尝试重新连接。建立初始连接后出错:Mongoose将尝试重新连接,并且它将发出“错误”事件。

  • 这是mongoose documentation的错误处理。*
    解决方案:您的案例需要监听error事件进行错误处理。
mongoose.connection.on("error", async (err) => {
  await _handleConnectionErrors(err)
});

字符串

Note如果答案没有帮助,请在评论中注明

yrwegjxp

yrwegjxp2#

对我来说,它现在正在工作:

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

字符串

相关问题