Little Child Little Child - 6 months ago 12
Node.js Question

Promises error handling basics

Suppose I have code like this, assuming

db.get()
is a promisified API:

var promises = [];
for( var i = 0; i < 10; i++ ){
promises.push( getFromDatabase("age") );
}
Q.all(promises).then(function(results){
// something
},function(error){
log.error( error )
});

function getFromDatabase(property){
return db.get(property).then(function(result){
return result;
},function(error){
log.error( error )
})
}


Who'll handle the error? The function in promise chain of
Q.all()
or the function in promise chain of
getFromDatabase()
.

Also, if there is a top level error handler like in
Q.all()
, is there a need for handling error in helper functions?

Answer

Who'll handle the error? The function in promise chain of Q.all() or the function in promise chain of getFromDatabase().

With your code in the question, errors will be handled by getFromDatabase()'s error handlers. But in your case, errors will also not propagate further to Q.all()'s one, because you basically handler error there and never pass error futher.

Also, if there is a top level error handler like in Q.all(), is there a need for handling error in helper functions?

It depends on your business logic, what behaviour you want from your app. Maybe you want to log error in inner getFromDatabase error handler, and pass failure further to the outer handler for proper error message for UI rendering. Up to you. But in this case you would need to rethrow error or return rejected promise from inner handler:

Q.all(promises).then(function(results){
    // something
},function(error){
    // Render error message for UI, etc.
});

function getFromDatabase(property){
    return db.get(property).then(function(result){
        return result;
    },function(error){
        // just log here
        log.error(error);
        throw error;
    })
} 
Comments