Return empty array or error

大兔子大兔子 提交于 2021-01-29 12:11:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!