使用 node-pg 处理查询错误

Handling query errors with node-pg

我正在尝试将两个查询插入到我的 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 (, , 0);';
    const query2 = 'INSERT INTO lineitems (wo_num, description, cost) VALUES (, , );';

    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 网络应用程序崩溃。我该如何处理这个错误,让它只向用户发送一条消息而不停止整个应用程序?

你应该在 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 (, , 0) ON CONFLICT (wo_id) DO NOTHING (https://www.postgresql.org/docs/9.5/sql-insert.html#SQL-ON-CONFLICT)