繁体   English   中英

node js function 连接到postgres返回错误

[英]node js function connect to postgres return error

我有这个 function。 查询成功时效果很好,但是当我收到错误时,我需要返回错误响应。 我已经看到了一些使用 res.json 的示例,但在 catch 中不提供 res。 如何向此 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);

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

 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM