2016-10-04 81 views
1

你好我是Postgresql的新手,我想知道如何處理0結果作爲錯誤被拋出。基本上我想要一個用戶,如果它不存在,返回null如果沒有,並且有一個錯誤處理程序。以下是我正在使用的當前代碼。任何提示,以更好的方式來做到這一點,表示讚賞!Node/Express&Postgresql - 當沒有行匹配時

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

你使用哪個節點postgres模塊? – Paul

+0

pg-promise –

+0

如果找不到該行是正常情況(不是錯誤),則應該使用方法'oneOrNone',並檢查已解析的值爲null。使用'.catch'來處理實際的錯誤。 –

回答

2

我的pg-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; 
     } 
    }); 

類似的考慮都選擇方法many當VS manyOrNone(方法制造是manyOrNone的更短的別名)。

類型QueryResultError有一個非常友好的控制檯輸出,就像庫中的所有其他類型一樣,可以幫助您瞭解如何處理這種情況。

+1

感覺pg-promise的作者有點榮幸回答了這個問題。感謝Vitaly-t! –

1

在爲查詢您的catch處理程序,只是測試了這個錯誤。縱觀pg-promise源代碼,無數據的代碼是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); 
     });