如何根据 pg-promise 事务中查询失败的位置执行不同的错误消息?

How to execute different error messages depending on where a query failed in a transaction in pg-promise?

如何根据事务中查询失败的位置触发回滚来执行不同的错误消息?

我将使用文档中的示例代码:

db.tx(t => {
    // creating a sequence of transaction queries:
    const q1 = t.none(query);
    const q2 = t.one(query);
    const q3 = t.one(query);

    // returning a promise that determines a successful transaction:
    return t.batch([q1, q2, q3]); // all of the queries are to be resolved;
})
    .then(data => {
        // success, COMMIT was executed
    })
    .catch(error => {
        // failure, ROLLBACK was executed
    });

首选输出如下:

res.json({error: true, message:"q1 failed"})
res.json({error: true, message:"q2 failed"})
res.json({error: true, message:"q2 failed"}), etc.

我在想的是使用 Switch 语句来确定要执行的错误消息,尽管我不知道如何知道什么查询在交易。

感谢您的帮助!

P.S。我最近从 node-pg 迁移到 pg-promise(这就是为什么我对 API 有点陌生)因为我以前的帖子中推荐的事务很难处理,是的,pg-promise使很多事情变得更容易 1 天的重构代码是值得的。

由于您使用的方法 batch, you get BatchError 在方法失败时抛出,这很有用 属性 data,其中包括:

.catch(err => {
    // find index of the first failed query:
    const errIdx = err.data.findIndex(e => !e.success);

    // do what you want here, based on the index;
});

请注意,在此类错误处理程序中,err.data[errIdx].resulterr.first 相同,表示发生的第一个错误。