Skip to content Skip to sidebar Skip to footer

Catching Errors Generated In Promises Within Promises In Javascript

Is it possible to have errors bubble up in Promises? See the code below for reference, I'd like to get promise1.catch to catch the error generated in promise2 (which current does n

Solution 1:

Yes!!

Error propagation in promises is one of its strongest suits. It acts exactly like in synchronous code.

try { 
    thrownewError("Hello");
} catch (e){
    console.log('Caught here, when you catch an error it is handled');
}

Is very similar to:

Promise.try(function(){
    thrownewError("Hello");
}).catch(function(e){
    console.log('Caught here, when you catch an error it is handled');
});

Just like in sequential code, if you want to do some logic to the error but not mark it as handled - you rethrow it:

try { 
   thrownewError("Hello");
} catch (e){
    console.log('Caught here, when you catch an error it is handled');
    throw e; // mark the code as in exceptional state
}

Which becomes:

var p = Promise.try(function(){
   thrownewError("Hello");
}).catch(function(e){
    console.log('Caught here, when you catch an error it is handled');
    throw e; // mark the promise as still rejected, after handling it.
});

p.catch(function(e){
     // handle the exception
});

Note that in Bluebird you can have typed and conditional catches, so if all you're doing is an if on the type or contents of the promise to decide whether or not to handle it - you can save that.

var p = Promise.try(function(){
   thrownewIOError("Hello");
}).catch(IOError, function(e){
    console.log('Only handle IOError, do not handle syntax errors');
});

You can also use .error to handle OperationalErrors which originate in promisified APIs. In general OperationalError signifies an error you can recover from (vs a programmer error). For example:

var p = Promise.try(function(){
   thrownewPromise.OperationalError("Lol");
}).error(function(e){
    console.log('Only handle operational errors');
});

This has the advantage of not silencing TypeErrors or syntax errors in your code, which can be annoying in JavaScript.

Post a Comment for "Catching Errors Generated In Promises Within Promises In Javascript"