Joonas Alhonen
Joonas Alhonen

Reputation: 332

How to handle errors on async NodeJS application

I've been migrating from PHP to NodeJS and I love it. For example, I'm using MySQL and the more queries (async events) I run, code becomes more cluttered:

db.execute("SQL query", [params], (err, rows) => {
    if(err) {
        console.log("error happened");
    }
    else {
        db.execute("other query", [params], (err, rows) => {
            if(err) {
                console.log("another error happened");
            }
            else {
                console.log("success");
            }
        });
    }
});

With my coding style one query equals 7+ rows of code which I think is way too much. How do you guys handle this kind of code? Do you guys use some kind of global "on error" event which fires when any of the queries fails and you just assume in the code that everything has worked prior to this point. I was thinking something like this:

function onError() {
    console.log("an error happened");
}

db.execute("SQL query", [params], (onError, rows) => {
    db.execute("other query", [params], (onError, rows) => {
        console.log("success");
    });
});

Upvotes: 2

Views: 76

Answers (1)

libik
libik

Reputation: 23029

The Promises (look to ES6 Promises or find Bluebird package) are the answer. You just chain them one after another and one of the thing I love - no more "if (error)". You define Catch method, where you catch errors. And one catch is enough for the whole chain of queries.

Upvotes: 3

Related Questions