首页 > 解决方案 > 如何在没有 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) 。但是对于那个问题,提问者没有任何异常处理程序/捕获块。

标签: javascriptnode.jspromisetry-catch

解决方案


看起来您从中调用的 try-catch 块db.dmlClips不在async函数内。在没有 async 关键字的函数中声明的 Try-catch 不会捕获 Promise 拒绝。


推荐阅读