4/29/13

subtle bug


a node module I'm using has some code like this:


function (x, y, callback) {
    var data = ...get some data based on x and y...
    try {
        var json = JSON.parse(data)
        return callback(null, json)
    } catch (error) {
        return callback(error)
    }
}

the idea is to get some data, and try to parse it as json, and if the parsing succeeds, pass the parsed object to the callback, otherwise, send the parse error to the callback.

however: if the callback code itself throws an error, this is also caught, and the callback is called again with the error that it just threw.

I think the code should look like this instead, where the call to the callback has been taken outside the try/catch

function (x, y, callback) {
    var data = ...get some data based on x and y...
    try {
        var json = JSON.parse(data)
    } catch (error) {
        return callback(error)
    }
    return callback(null, json)
}


No comments:

Post a Comment