node.js - UnhandledPromiseRejectionWarning 即使代码在 async/await 中有 try/catch

标签 node.js error-handling promise async-await

我意识到这可能看起来像是其他问题的重复,但在发布此内容之前,我已经查看了我能找到的每个建议的SO问题,并且我正在寻找有关此特定场景的帮助,因为其他答案都不起作用对我来说。

我有一个 Node/Express 应用程序正在初始化一个供 REST API 使用的 MongoDB 连接。第一步是连接到 MongoDB 实例。如果初始连接失败,它将按预期抛出错误。我使用 async/await 和内部的 try/catch block 来处理这个问题。我看过的所有地方都说这应该足以捕获这些 async/await promise 拒绝,但无论我在哪里输入 .catch() ,我都会收到有关 UnhandledPromiseRejection 的错误。或尝试/捕获我的代码(如其他 SO 帖子中的建议)。

例如,在此链接中,我的错误处理部分中描述的内容几乎相同,但问题仍然存在。

https://javascript.info/async-await

这是错误(我知道是什么导致了错误本身 - 我现在停止了 MongoDB 服务 - 但我正在尝试修复未处理的 promise 拒绝错误):

(node:15633) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:15633) [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. (node:13802) UnhandledPromiseRejectionWarning: MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] at Pool.<anonymous> (/home/allen/scripts/lysi/eosMain/node_modules/mongodb-core/lib/topologies/server.js:562:11) at Pool.emit (events.js:189:13) at Connection.<anonymous> (/home/allen/scripts/lysi/eosMain/node_modules/mongodb-core/lib/connection/pool.js:316:12) at Object.onceWrapper (events.js:277:13) at Connection.emit (events.js:189:13) at Socket.<anonymous> (/home/allen/scripts/lysi/eosMain/node_modules/mongodb-core/lib/connection/connection.js:245:50) at Object.onceWrapper (events.js:277:13) at Socket.emit (events.js:189:13) at emitErrorNT (internal/streams/destroy.js:82:8) at emitErrorAndCloseNT (internal/streams/destroy.js:50:3) at process._tickCallback (internal/process/next_tick.js:63:19)

这是我的代码:

exports.mongoConnect = async (dbName, archiveDbName, userName, password) => {

    // Auth params
    const user = encodeURIComponent(userName);
    const pass = encodeURIComponent(password);
    const authMechanism = 'DEFAULT';

    // Connection URL
    const url = `mongodb://${user}:${pass}@localhost:27017?authMechanism=${authMechanism}&authSource=admin`;
    let client;

    try {
        // Use connect method to connect to the Server
        client = await MongoClient.connect(url, { useNewUrlParser: true, poolSize: 10, autoReconnect: true, reconnectTries: 6, reconnectInterval: 10000 }).catch((e) => { console.error(e) });

        db = client.db(dbName);
        archiveDb = client.db(archiveDbName);

        console.log(`Succesfully connected to the MongoDb instance at URL: mongodb://localhost:27017/ with username: "` + client.s.options.user + `"`);
        console.log(`Succesfully created a MongoDb database instance for database: "` + db.databaseName + `" at URL: mongodb://localhost:27017/`);
        console.log(`Succesfully created a MongoDb database instance for database: "` + archiveDb.databaseName + `" at URL: mongodb://localhost:27017/`);
    } catch (err) {
        console.log(`Error connecting to the MongoDb database at URL: mongodb://localhost:27017/` + dbName);
    }
}

这是从 app.js 调用的,如下所示:

mongoUtil.mongoConnect('myDb', 'myArchiveDb', 'myUser', 'myPassword');

我什至尝试将该行放入 try/catch block 中,或添加 promise 样式 .catch()到最后,没有任何改变。

我似乎不明白为什么它仍然提示没有处理 promise 拒绝。

编辑:

这是整个 app.js 文件:

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var cors = require('cors');
var app = express();

const MongoClient = require('mongodb').MongoClient;
// This is where the mongo connection happens
var mongoUtil = require( './services/mongoUtil' );
var bluebird = require('bluebird');

const jwt = require('./helpers/jwt');

var api = require('./routes/api.route')

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(cors());
app.use(logger('dev'));
app.use(express.json()); 
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/api', api);

// use JWT auth to secure the api
app.use(jwt());

app.use('/users', require('./users/users.controller'));

MongoClient.Promise = bluebird

mongoUtil.mongoConnect('myDb', 'myArchiveDb', 'username', 'password');

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  next();
});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;`

最佳答案

我测试了您的代码,它工作正常,如下面的屏幕截图所示。我认为问题在于调用 mongoConnect() 的任何内容

Connecting on wrong port Successful connection

关于node.js - UnhandledPromiseRejectionWarning 即使代码在 async/await 中有 try/catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54600681/

相关文章:

node.js - 由heroku调度程序创建的一次性dyno永远不会死(永远不会自杀,自杀......)

javascript - 如何每天在 11 :00pm 在 Node js 中运行 API GET 调用

javascript - Angular 动态模板指令

javascript - 重复模板

javascript - 如何在nodejs中保持JSON数字键的顺序

php - 如何在apache的自定义错误响应包中包含错误文档的页眉和页脚?

error-handling - Ansible-在循环执行任务期间检查任务是否失败

javascript - .getJSON 与 .ajax 错误处理

jquery - 延迟 Angular 的状态?

javascript - 从 Promise 的 catch 添加到现有的 Promises.all 数组