此连接预计会出错,但我应该能够拒绝承诺。但是,我得到的未经处理的结果承诺拒绝。 (我按照预期从console.log()获得了双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.
答案 0 :(得分:1)
你不应该把错误扔进catch。
.catch(e => {
console.log(e);
process.exit(1); // to exit with no error use 0
});
Express.js中抛出的错误将关闭您的应用程序。