我正在尝试调用异步方法。异步方法是:
async connect() {
this.pool = await mysql.createPool(this.conf);
await this.pool.getConnection().catch((err) => { throw new Error(err) });
}
调用这个方法的代码是:
(async () => {
await db.connect()
.catch((err) => {
console.error(`Database connection error: ${err.message}`);
throw new Error(err);
});
})();
但是,当 this.pool.getConnection() 中发生错误时,我收到以下警告:
[Thu Jun 13 2019 23:10:59] [ERROR] (node:18296) UnhandledPromiseRejectionWarning: Error: Error: Access denied for user 'root'@'localhost' (using password: YES)
at pool.getConnection.catch
at process._tickCallback
[Thu Jun 13 2019 23:10:59] [ERROR] (node:18296) 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)
[Thu Jun 13 2019 23:10:59] [ERROR] (node:18296) [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.
阅读了类似问题的答案后,我明白必须处理来自 Promises 的拒绝,但是我不知道我没有正确处理这个问题的地方。this.pool.getConnection() 调用有一个 catch 块,在那里我抛出错误,所以它被传递给匿名调用函数来处理。
我已经尝试了此代码的几种变体,包括向匿名函数本身添加一个 catch 块并在那里再次抛出错误,但似乎没有任何效果,并且警告总是源自 this.pool.getConnection() 调用。
我试图实现的是将 connect() 方法中发生的任何错误传递给匿名函数进行处理。
我哪里错了?提前致谢。
编辑:有趣的是,如果我按如下方式编写 this.pool.getConnection() 行(catch 块中没有任何内容),警告就会消失:
await this.pool.getConnection().catch((err) => {});
当我尝试在箭头函数内执行任何操作时,例如将错误分配给变量,警告再次出现。
慕田峪7331174
森栏
相关分类