Skip to content

Instantly share code, notes, and snippets.

@harish2704
Created June 22, 2017 06:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harish2704/90651dbe32b63fe6cdc1c62db14f2b89 to your computer and use it in GitHub Desktop.
Save harish2704/90651dbe32b63fe6cdc1c62db14f2b89 to your computer and use it in GitHub Desktop.
catchIf syntax sugar for ES6 Promise. can be applied to any Promise library
/*
Adds a catchIf method to Promise.
Usage
Promise.reject( new TypeError() )
.catchIf( TypeError, function handler(err){ console.log('TypeError handled')} )
.catchIf( RangeError, function handler(err){ console.log('RangeError handled')} )
*/
function addCatchIf ( promiseClass ){
promiseClass.prototype.catchIf = function(){
const args = [];
let i = arguments.length;
if( i === 1 ){
return this.catch( arguments[ 0 ] );
}
while( i-- ){
args[ i ] = arguments[ i ];
}
const handler = args.pop();
return this.catch(function(err){
let i;
const l = args.length;
for ( i = 0; i < l; i++ ) {
if( err instanceof args[ i ] ){
return handler( err );
}
}
return promiseClass.reject(err);
});
};
}
addCatchIf( Promise );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment