gpt4 book ai didi

javascript - 错误: Uncaught (in promise): Unhandled promise rejections

转载 作者:行者123 更新时间:2023-12-03 01:49:16 27 4
gpt4 key购买 nike

此连接预计会出错,但我应该能够捕获 promise 拒绝。但我得到的结果是未处理的 promise 拒绝。 (正如预期的那样,我从 console.log() 得到了 double mongoError )感谢您的建议和建议。

mongodbModule.js 文件

var connection;
module.exports.mongodbConnect = () => {
return new Promise(async (resolve, reject) => {
if (!connection) {
try {
connection = await mongoClient.connect(uri, opts);
let database = connection.db(dbName);
resolve(database)
} catch (mongoErr) {
console.log(mongoErr);
reject(mongoErr);
}
}
});
};

app.js

const mongoConnect = require('./modules/mongodbModule').mongodbConnect;
const connectDb = () => {
return new Promise( async (resolve,reject) => {
try {
let db = await mongoConnect()
resolve(db);
} catch (err) {
reject(err);
}
});
};

connectDb()
.then((db) => {
console.log(db)
})
.catch((mongoErr) => {
console.log(mongoErr)
throw mongoErr;
});

错误

(node:26864) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
(node:26864) [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.

最佳答案

您不应该将错误抛出到 catch 中。

.catch(e => {
console.log(e);
process.exit(1); // to exit with no error use 0
});

Express.js 中抛出的错误将关闭您的应用程序。

关于javascript - 错误: Uncaught (in promise): Unhandled promise rejections,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50488403/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com