【问题标题】:Handling query errors with node-pg使用 node-pg 处理查询错误
【发布时间】:2021-09-03 05:57:30
【问题描述】:

我正在尝试将两个查询插入到我的 postgres 数据库中,如下所示:

const insertLineItemDB = (request, response) => {
    const { wo_num, description, due_date, cost } = request.body
    const query1 = 'INSERT INTO workorders (wo_id, due_date, complete) VALUES ($1, $2, 0);';
    const query2 = 'INSERT INTO lineitems (wo_num, description, cost) VALUES ($1, $2, $3);';

    Promise.all([
        pool.query(query1, [wo_num, due_date]),
        pool.query(query2, [wo_num, description, cost])
    ]).then(function([query1Results, query2Results]) {
        response.status(201).send('Successfully inserted');
    });
}

我的问题是我收到以下错误:error: duplicate key value violates unique constraint "workorders_pkey" 导致我的 node 网络应用程序崩溃。如何处理此错误,以便它只向用户发送一条消息但不停止整个应用程序?

【问题讨论】:

    标签: javascript node.js express node-pg-pool


    【解决方案1】:

    你应该在 Promise 中发现错误

    Promise.all([
        pool.query(query1, [wo_num, due_date]),
        pool.query(query2, [wo_num, description, cost])
    ]).then(function([query1Results, query2Results]) {    
        response.status(201).send('Successfully inserted');
    }).catch(function (e) {
        response.status(500).send('Insert failed');
    });
    

    你也可以将你的 Promise 包装在 try catch 块中

    try {
        Promise.all([
            pool.query(query1, [wo_num, due_date]),
            pool.query(query2, [wo_num, description, cost])
        ]).then(function([query1Results, query2Results]) {    
             response.status(201).send('Successfully inserted');
        })
    } catch(e) {
        response.status(500).send('Insert failed');
    }
    

    有点不是你问的,但你也可以忽略重复键

    INSERT INTO workorders (wo_id, due_date, complete) VALUES ($1, $2, 0) ON CONFLICT (wo_id) DO NOTHING (https://www.postgresql.org/docs/9.5/sql-insert.html#SQL-ON-CONFLICT)
    

    【讨论】:

    • 完美,谢谢。忽略重复键实际上正是我所需要的
    猜你喜欢
    • 2021-11-02
    • 2012-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 2021-07-11
    • 1970-01-01
    相关资源
    最近更新 更多