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

rbl8hiat  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(506)

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

/**
 * 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方面的一些基本知识。欢迎任何帮助:)

wpcxdonn

wpcxdonn1#

既然你没有 await.then 随叫随到 insertData ,异常可能不会在代码退出之前抛出 try
我已经将代码简化为一个可以在更高的函数中捕获错误的javascript示例。
我们回报了他们的承诺 insertData 我们 .catch 在这个承诺的基础上

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> 打字游戏场
这是一个带有async/await的版本,其中的关键是两者都是 async 而且是 await 他在街上走着 try

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();

相关问题