无法捕获 then 块中抛出的错误

Unable to catch error thrown in then block

我试图在使用 knex 向数据库中添加条目时捕获错误。错误在 insertData 箭头函数的 catch 块中正确捕获并记录在控制台中。但是,当我在那里抛出另一个错误以将其冒泡到下一个函数(handleIncomingData)时,它没有被正确捕获并且我得到 UnhandledPromiseRejectionWarning。这是两个函数的代码。

/**
 * Wrapper function for inserting data into the database
 * @param data
 * @param tableName
 * @param formatMethod
 */
const insertData = (data, tableName, formatMethod) => {
    knex(tableName).insert(formatMethod(data))
        .then(() => console.log(`Entries added to ${ tableName }`))
        .catch((err) => { console.log(err); throw err;})
}

/**
 * Handle the incoming data
 * @param data
 */
const handleIncomingData = (data) => {
    const { item, sales_line_discount, sales_price, campaign_target_group, } = data;
    
    try {
        if (item) {
            insertData(item, 'item', formatItems);
        }
    } catch (err) {
        console.log(err);
    }
}

我也复制了错误:

Error: insert into `item` (`base_unit_of_measure`, `blocked`, `item_disc__group`, `last_date_modified`, `sku`, `unit_price`) values ('M', 0, 'DE05', '2018-09-05', '0100444', '5.593') - Duplicate entry '0100444' for key 'item.items_sku_uindex'
    at Packet.asError (/home/sw/Projects/navision-middleware/node_modules/mysql2/lib/packets/packet.js:712:17)
    at Query.execute (/home/sw/Projects/navision-middleware/node_modules/mysql2/lib/commands/command.js:28:26)
    at Connection.handlePacket (/home/sw/Projects/navision-middleware/node_modules/mysql2/lib/connection.js:425:32)
    at PacketParser.onPacket (/home/sw/Projects/navision-middleware/node_modules/mysql2/lib/connection.js:75:12)
    at PacketParser.executeStart (/home/sw/Projects/navision-middleware/node_modules/mysql2/lib/packet_parser.js:75:16)
    at Socket.<anonymous> (/home/sw/Projects/navision-middleware/node_modules/mysql2/lib/connection.js:82:25)
    at Socket.emit (events.js:314:20)
    at addChunk (_stream_readable.js:297:12)
    at readableAddChunk (_stream_readable.js:272:9)
    at Socket.Readable.push (_stream_readable.js:213:10) {
  code: 'ER_DUP_ENTRY',
  errno: 1062,
  sqlState: '23000',
  sqlMessage: "Duplicate entry '0100444' for key 'item.items_sku_uindex'"
}
(node:70871) UnhandledPromiseRejectionWarning: Error: insert into `item` (`base_unit_of_measure`, `blocked`, `item_disc__group`, `last_date_modified`, `sku`, `unit_price`) values ('M', 0, 'DE05', '2018-09-05', '0100444', '5.593') - Duplicate entry '0100444' for key 'item.items_sku_uindex'
    at Packet.asError (/home/sw/Projects/navision-middleware/node_modules/mysql2/lib/packets/packet.js:712:17)
    at Query.execute (/home/sw/Projects/navision-middleware/node_modules/mysql2/lib/commands/command.js:28:26)
    at Connection.handlePacket (/home/sw/Projects/navision-middleware/node_modules/mysql2/lib/connection.js:425:32)
    at PacketParser.onPacket (/home/sw/Projects/navision-middleware/node_modules/mysql2/lib/connection.js:75:12)
    at PacketParser.executeStart (/home/sw/Projects/navision-middleware/node_modules/mysql2/lib/packet_parser.js:75:16)
    at Socket.<anonymous> (/home/sw/Projects/navision-middleware/node_modules/mysql2/lib/connection.js:82:25)
    at Socket.emit (events.js:314:20)
    at addChunk (_stream_readable.js:297:12)
    at readableAddChunk (_stream_readable.js:272:9)
    at Socket.Readable.push (_stream_readable.js:213:10)
(node:70871) 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: 2)
(node:70871) [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.

据我所知,错误应该刚刚出现。我不知道如何调试它。我想这不是 knex 特有的东西,而是缺乏 JS 的一些基本知识。非常欢迎任何帮助:)

由于您在调用 insertData 时没有 await.then,因此可能不会在 try 块中的代码之前抛出异常。

我已将代码简化为一个工作 JavaScript 示例,能够在更高的函数中捕获错误。

  1. 我们return来自insertData
  2. 的承诺
  3. 我们.catch return 承诺

const insertData = () => {
    return new Promise((resolve, reject) => setTimeout(() => reject('oops')))
        .then(() => console.log(`Entries added`))
        .catch((err) => { console.log(`insertData: ${err}`); throw err;})
}

const handleIncomingData = () => {
    insertData().catch((err) => console.log(`handleIncomingData: ${err}`))
}

handleIncomingData();

TypeScript 与 new Promise<void> 完全相同 TypeScript Playground

这是一个带有 async/await 的版本,其中的关键是两者都是 async 并且在 try 块中被 awaited。

const insertDataA = async() => {
  try {
    await new Promise((resolve) => setTimeout(() => resolve()));
    throw 'oops';
  } catch (err) {
    console.log(`insertDataA: ${err}`);
    throw err;
  }
}

const handleIncomingDataA = async() => {
  try {
    await insertDataA();
  } catch (err) {
    console.log(`handleIncomingDataA: ${err}`);
  }
}

handleIncomingDataA();