【问题标题】:node js function connect to postgres return error节点js函数连接到postgres返回错误
【发布时间】:2020-06-28 02:47:01
【问题描述】:

我有这个功能。查询成功时效果很好,但是当我收到错误时,我需要返回错误响应。我已经看到了一些使用 res.json 的示例,但 res in 在 catch 中不可用。如何向此 api 的用户返回错误响应。

     pg.Client = config;
            client = await pool.connect();
            pool.connect()
            .then(client => {
                return client.query(query)
                    .then(res => {
                        client.release();
                        return res.rows;
                    })
                    .catch(e => {
                        client.release();
                        console.log(e.stack);
                    })
          }).finally(() => client.close);

【问题讨论】:

    标签: javascript node.js postgresql


    【解决方案1】:

    您的代码看起来很乱,您可以使用以下语法来集中查询:

     pool.connect((err, client, release) => {
          if (err) {
            return console.error('Error acquiring client', err.stack)
          }
          client.query('SELECT NOW()', (err, result) => {
            release()
            if (err) {
              return console.error('Error executing query', err.stack)
            }
            console.log(result.rows)
          })
        })
    

    请查看此文档:https://node-postgres.com/api/pool

    【讨论】:

    • 我同意不那么混乱。但是这仍然不会向客户端返回错误响应。这是客户端代码post("application", row_obj) .toPromise().then(()=> this.notice.success()).catch (error=> this.notice.error("Update failed"))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 2019-03-06
    • 2019-05-21
    • 1970-01-01
    • 2022-01-27
    • 2017-01-04
    • 2018-10-06
    相关资源
    最近更新 更多