问题
I have nodejs accessing a database to retrieve a row of orders. The following function is defined in a file called orderDb.js
module.exports.getWaitingOrders = function getWaitingOrders(callback) {
pool.query("SELECT * FROM live_order_table WHERE isWaiting = 1;", function(err, rows, fields) {
if (err) {
return new Error('Db error: ' + err);
}
if (rows.length <= 0) {
return new Error("No results"); //Is this recommended?
return [];// or this?
}
rows.forEach(function(row) {
var order = {
orderID: row.order_id
}
});
}
}
When nothing is returned from the database, should I return an error or an empty array/object?
I'm calling the method like this:
orderDb.getWaitingOrders(function handleWaitingOrders(err, orders){});
I also have a question on how to handle database issues. What i'm doing now, is to log the error and retry later. Is there a better practice i should be following?
回答1:
You should return an empty array or null so that you can identify an error with your database
module.exports.getWaitingOrders = function getWaitingOrders(callback) {
pool.query("SELECT * FROM live_order_table WHERE isWaiting = 1;", function(err, rows, fields) {
if (err) {
return new Error('Db error: ' + err) ;
}
if (rows.length <= 0) {
callback(err , []); // you should return an empty response here so that you can differentiate between error and no order
}
rows.forEach(function(row) {
var order = {
orderID: row.order_id
}
});
}
}
orderDb.getWaitingOrders(function handleWaitingOrders(err, orders){
// do your error handling here
});
来源:https://stackoverflow.com/questions/24852784/return-empty-array-or-error