javascript - 如何在没有 UnhandledPromiseRejectionWarning 的情况下从 Promise 向调用者抛出异常
问题描述
catch
考虑这个包含块的数据库查询处理程序:
async function dml(pool, sql, expected = -1) {
p(sql)
let rowCnt = await pool.query(sql)
.then(r => {
if (expected >= 0 && r.rowCount != expected) {
throw `DML [${sql}] had wrong number of results: ${r.rowCount} vs expected=${expected}`
} else {
return r.rowCount
}
})
.catch(err => {
msg = `Query [${sql}] failed: ${err}`;
printError(msg,err)
throw msg // THIS is the problem. It generates UnhandledPromiseRejection
}
return rowCnt
}
抛出的异常旨在由调用者在此处捕获:
async function handleClip(data) {
..
// calling code
try {
// ...
let cnt = db.dmlClips(sql, 1) // Throw() happens in this invocation
debug(`Update count is ${cnt}`)
return rcode
} catch (err) {
// WHY is the thrown exception not caught here??
let msg = `Error in handleClip for data=${data.slice(0,min(data.length,200))}`;
error(msg,err);
}
但上述结构显然是不可接受的:产生以下严重警告:
(node:39959) UnhandledPromiseRejectionWarning: Query [insert into clip ...] failed: error: role "myuser" does not exist
at emitUnhandledRejectionWarning (internal/process/promises.js:170:15)
at processPromiseRejections (internal/process/promises.js:247:11)
at processTicksAndRejections (internal/process/task_queues.js:94:32)
(node:39959) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict`
(see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:39959) [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.
at emitDeprecationWarning (internal/process/promises.js:180:11)
at processPromiseRejections (internal/process/promises.js:249:13)
at processTicksAndRejections (internal/process/task_queues.js:94:32)
那么这需要如何设置呢?注意这里有一个相关的问题:如果 promise 被拒绝,如何正确抛出错误?(UnhandledPromiseRejectionWarning) 。但是对于那个问题,提问者没有任何异常处理程序/捕获块。
解决方案
看起来您从中调用的 try-catch 块db.dmlClips
不在async
函数内。在没有 async 关键字的函数中声明的 Try-catch 不会捕获 Promise 拒绝。
推荐阅读
- python - 如何更改将行值添加到列的 pd DataFrame 的结构?
- php - 如何在电子邮件中发送嵌入的pdf
- node.js - 推送到MongoDB中的数组
- python - 使用 Python 生成点并丢弃前几个点
- sql - 在 SQL Server 中的计算列上运行总计
- reverse-engineering - ghidra DAT_* 中的问号
- javascript - 无法在 MDEditor 中输入值
- android - 操作系统可以杀死静态广播接收器吗?
- python - 字典中的列表中只有 1x 值
- arduino - 如何缩小使用 DHT11 进行 AVR 的代码(Attiny45)