当MongoDB连接失败时,应用程序会崩溃,尽管它周围有Promise

tvokkenx  于 2023-04-29  发布在  Go
关注(0)|答案(1)|浏览(116)

当我使用正确的密码运行它时,它工作正常,只有使用不正确的密码时,它会抛出一个uncuaght异常,由于某种原因,这个异常没有被promise捕获,然后应用程序崩溃
这里是控制器tryCtrl。js

const connection = require('./tryDB');

connection
  .then(() => console.log('success'))
  .catch((error) => {
    console.error(error);
  });

下面是访问dbtryDB的模型文件。js

const mongoose = require('mongoose');

require('dotenv').config();

// create connection to db
const uri = process.env.MONGO_URI;

const connection = new Promise((resolve, reject) => {
  mongoose.connect(uri);
  const db = mongoose.connection;
  db.on('error', (error) => {
    reject(error);
  });
  db.once('open', () => {
    resolve(db);
  });
});

module.exports = connection;

当我用一个假密码运行它时,我希望expection被捕获,但它破坏了应用程序,这是错误:

node:internal/process/promises:288
        triggerUncaughtException(err, true /* fromPromise */);
        ^

MongoServerError: bad auth : authentication failed
    at Connection.onMessage (C:\Users\israe\Documents\GitHub\my-mongo\node_modules\mongodb\lib\cmap\connection.js:201:30)
    at MessageStream.<anonymous> (C:\Users\israe\Documents\GitHub\my-mongo\node_modules\mongodb\lib\cmap\connection.js:59:60)
    at MessageStream.emit (node:events:513:28)
    at processIncomingData (C:\Users\israe\Documents\GitHub\my-mongo\node_modules\mongodb\lib\cmap\message_stream.js:124:16)
    at MessageStream._write (C:\Users\israe\Documents\GitHub\my-mongo\node_modules\mongodb\lib\cmap\message_stream.js:33:9)
    at writeOrBuffer (node:internal/streams/writable:392:12)
    at _write (node:internal/streams/writable:333:10)
    at Writable.write (node:internal/streams/writable:337:10)
    at TLSSocket.ondata (node:internal/streams/readable:766:22)
    at TLSSocket.emit (node:events:513:28) {   ok: 0,   code: 8000,   codeName: 'AtlasError',   connectionGeneration: 0,  
[Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' } }

任何想法都值得赞赏

bq3bfh9z

bq3bfh9z1#

理想情况下,不应该导出引用Promises的变量。导出是指您以后要重用的功能或常量。你应该重新构造connection函数,返回一个Promise,如下所示:

const mongoose = require('mongoose');

require('dotenv').config();

// create connection to db
const uri = process.env.MONGO_URI;

const connection = () => new Promise((resolve, reject) => {
  mongoose.connect(uri);
  const db = mongoose.connection;
  db.on('error', (error) => {
    reject(error);
  });
  db.once('open', () => {
    resolve(db);
  });
});

module.exports = connection;

现在你的控制器变成这样:

const connection = require('./tryDB');

connection()
  .then(() => console.log('success'))
  .catch((error) => {
    console.error(error);
  });

请注意,我首先调用了connection函数,然后将promise函数链接起来。
更新:这是一个未捕获的异常。要捕获它,可以添加process.on事件处理程序。在你的应用里。js文件,像这样:

process
  .on('unhandledRejection', (reason, p) => {
    console.error(reason, 'Unhandled Rejection at Promise', p);
  })
  .on('uncaughtException', err => {
    console.error(err, 'Uncaught Exception thrown');
  });

请注意,这不是推荐的方法,理想情况下,您应该让应用程序在出现此类错误时停止。此外,您可以尝试按照mongoose here的创建者的建议设置mongoose.Promise = global.Promise;

相关问题