Node / Express&Postgresql – 当没有行匹配时

你好我是Postgresql的新手,我想知道如何处理0结果作为错误被抛出。 基本上我想获得一个用户,如果它不存在,返回null,如果没有,并有一个error handling程序。 以下是我正在使用的当前代码。 任何提示,以更好的方式来做到这一点,表示赞赏!

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'" } 

我是pg-promise的作者。


在承诺的范围内使用.then处理所有正常情况,并处理所有错误情况。

转换成pg-promise ,遵守这个规则,你执行一个数据库方法来parsing表示所有正常情况的结果,所以其他的结果都在.catch

例如,如果返回一个或没有行是您的查询的正常情况,您应该使用方法oneOrNone 。 只有当返回没有行是无效的情况下,你会使用方法一 。

按照API,方法oneOrNone用find的数据行解决,或者在找不到任何行时用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; } }); 

当select方法许多或许多 (方法任何是许多或更短的别名)时,类似的考虑。

typesQueryResultError有一个非常友好的控制台输出,就像库中的其他types一样,给你一个关于如何处理这种情况的好主意。

在查询的catch处理程序中,只需testing该错误。 看看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); });