« Back to Index

Demonstrate how to handle bubbling errors by consolidating them (modified from: http://blog.ponyfoo.com/2013/07/12/teach-yourself-nodejs-in-10-steps)

View original Gist on GitHub

bubbling errors.js

function sum(a, b, done) {
    // we convert this otherwise sync function into an async function
    // note: this forces itself into the next event loop
    //       we should use setImmediate instead which places it at 
    //       the bottom of the current event loop stack
    process.nextTick(function() {
        // `done` is the callback function passed into `sum`
        done(null, a + b)
    });
}

function then(err, result) {
    if (err) throw err

    // `console.log` is an alias to stdout plus automatically adds a new line
    // but I prefer the long format just to be explicit
    process.stdout.write('Result: ' + result + '\n'); // the new line prevents the shell from displaying an ugly % character
}

// if we use the typical style of error handling
// where we throw an error from the callback handler
// then the following example wouldn't work that great
// because we'd be throwing multiple errors up the stack.
// it's better if we consolidate the error handling in one place.
// see the use of the `then` function which does this consolidation.
sum(1, 2, function(err, result) {
    if (err) return then(err)

    sum(result, 3, function(err, result) {
        if (err) return then(err)

        then(null, result);
    });
});