【问题标题】:Node / Express & Postgresql - when no rows matchNode / Express & Postgresql - 当没有行匹配时
【发布时间】:2017-02-12 02:15:38
【问题描述】:

您好,我是 Postgresql 的新手,我想了解在抛出错误时如何处理 0 结果。本质上,如果用户不存在,我想获取用户,如果不存在则返回 null,并有一个错误处理程序。以下是我正在使用的当前代码。任何关于更好的方法的提示都非常感谢!

var options = {
  // Initialization Options
  promiseLib: promise
};
var pgp = require('pg-promise')(options);
var connectionString = 'postgres://localhost:5432/myDbName';
var db = pgp(connectionString);

function getUser(id) {         
  let user = new Promise(function(resolve, reject) {
    try {
      db.one('select * from users where loginName = $1', id).then(function(data) {
        console.log(data);
        resolve(data); 
      }).catch (function (e) {
        console.log('error: '+e);
        reject(e);
      });
    }
    catch (e) {
      console.log('error: '+e);
      reject(e);
    }
  });
  return user;
}

控制台输出:

error: QueryResultError {
    code: queryResultErrorCode.noData
    message: "No data returned from the query."
    received: 0
    query: "select * from users where loginName = 'someUserName'"
}

【问题讨论】:

  • 你使用的是哪个节点的 postgres 模块?
  • pg-promise(添加到最近编辑的帖子中)
  • 如果没有找到该行是正常情况(不是错误),您应该改用方法oneOrNone,并检查null的解析值。使用.catch 处理实际错误。

标签: node.js postgresql pg-promise


【解决方案1】:

我是pg-promise的作者。


在 Promise 领域,使用.then 处理所有正常情况,使用.catch 处理所有错误情况。

转换为遵循该规则的pg-promise,您执行一个数据库方法,该方法使用代表所有正常情况的结果进行解析,因此其他任何事情都以.catch 结束。

例如,如果返回一行或不返回行是您查询的正常情况,您应该使用方法oneOrNone。只有当不返回任何行是无效情况时,您才会使用方法one

根据 API,方法 oneOrNone 使用找到的数据行解析,或者在没有找到行时使用 null 解析,您可以检查:

db.oneOrNone('select * from users where loginName = $1', id)
    .then(user=> {
        if (user) {
            // user found
        } else {
            // user not found
        }
    })
    .catch(error=> {
        // something went wrong;     
    });

但是,如果您的查询不返回任何数据确实表示错误,则检查不返回行的正确方法如下:

var QRE = pgp.errors.QueryResultError;
var qrec = pgp.errors.queryResultErrorCode;

db.one('select * from users where loginName = $1', id)
    .then(user=> {
        // normal situation;
    })
    .catch(error=> {
        if (error instanceof QRE && error.code === qrec.noData) {
            // found no row
        } else {
            // something else is wrong;
        }
    });

在选择方法manymanyOrNone 时,有类似的考虑(方法anymanyOrNone 的简称)。

类型QueryResultError 具有非常友好的控制台输出,就像库中的所有其他类型一样,可以让您很好地了解如何处理这种情况。

【讨论】:

  • 感到有点荣幸pg-promise的作者回答了这个问题。谢谢 Vitaly-t!
【解决方案2】:

在查询的 catch 处理程序中,只需测试该错误。查看pg-promise源代码,noData 的代码为0。所以只需这样做:

db.one('select * from users where loginName = $1', id).then(function(data) {
        console.log(data);
        resolve(data); 
      }).catch (function (e) {
        if(e.code === 0){
          resolve(null);
        }
        console.log('error: '+e);
        reject(e);
      });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 2016-09-06
    • 2021-10-07
    • 2022-12-12
    • 2015-06-30
    • 2020-11-01
    • 2017-06-16
    相关资源
    最近更新 更多