Notifying caller about error from callback in node.js on error from sqlite3 call

183 views Asked by At

In node.js + sqlite3:

What is a good way to notify a caller from a callback about errors and get the caller to try again ? When we get a database locked error - would like to try and run the query again.

TestController.prototype.addDevices = function (number_of_devices, callback_after_all_devices_have_been_added) {
    var controller = this;
    var db = controller.connectToDb();

    for(i = 0; i < number_of_devices; i++) {
        db.each("SELECT api_key as ak FROM user_table ORDER BY RANDOM() LIMIT 1", function(err, row) {
            //sometimes we get a SQLITE: database locked error
            if (err !== null) {
                console.log("Error found");
                //i-- this will not work - but how do we do it then?
                return;
            }
            console.log("Error: " + err);
            //code to process if we get an entry from the user_table ..
        });
    }
}
1

There are 1 answers

2
saraf On

This is how I managed to solve this - added a retry counter and moved the problem code to its own function, passing in the epilogue as a callback. It works - but is this a good way? (other than using promises or the async module?)

TestController.prototype.addDevices = function (number_of_devices, callback_after_all_devices_have_been_added) {
    var number_of_users = 0;
    var controller = this;
    controller.pending_db_writes_for_device = number_of_devices;

    for(i = 0; i < number_of_devices; i++) {
        var api_key = controller.getRandomAPIKeyFromDB(10,function(access_key) {
            var mac_address = controller.generateRandomMAC();
            var friendly_name = Faker.random.array_element(["Washing Machine","Television","Dishwasher","Set top box"]);
            var description = Faker.Lorem.sentence(5);
            controller.registerDeviceWithAPI(mac_address, friendly_name, description, access_key, callback_after_all_devices_have_been_added);
        });
    }
}

TestController.prototype.getRandomAPIKeyFromDB = function (retry_counter, callback) {
  var controller = this;
  var db = controller.connectToDb();
  console.log("Retry counter: "+ retry_counter);
  db.each("SELECT api_key as ak FROM user_table ORDER BY RANDOM() LIMIT 1", function(err, row) {
            if (err !== null) {
                console.log("Error: " + err + "retry count: "+ retry_counter);
                console.log("Error found");
                if(retry_counter === 0) {
                    console.log("Bailing out after retry limit reached");
                    return;
                }
                controller.getRandomAPIKeyFromDB(--retry_counter,callback);
            }
            else {
                console.log("Successfully got api key: " + row.ak);
                callback(row.ak);
            }
        }
    );
}