Skip to content

Instantly share code, notes, and snippets.

@craig552uk
Created February 15, 2016 15:23
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 craig552uk/7d4032bbfbcf33f64205 to your computer and use it in GitHub Desktop.
Save craig552uk/7d4032bbfbcf33f64205 to your computer and use it in GitHub Desktop.
The Right and Wrong way to use Errors in Promises
//
// Wrong ways to use Errors in Promises
//
// Passes Error constructor to next step in Promise chain
Promise.resolve('foo').then(val => {
return Error('Bad Thing 1');
}).then(val => {
console.log('LOG 1', val);
}).catch(err => {
console.error('ERR 1', err);
});
// Passes Error Instance to next step in Promise chain
Promise.resolve('foo').then(val => {
return new Error('Bad Thing 2');
}).then(val => {
console.log('LOG 2', val);
}).catch(err => {
console.error('ERR 2', err);
});
// Swallows Error constructor
// Passes undefined to next step in Promise Chain
Promise.resolve('foo').then(val => {
Promise.reject(Error('Bad Thing 3'));
}).then(val => {
console.log('LOG 3', val);
}).catch(err => {
console.error('ERR 3', err);
});
// Swallows Error Instance
// Passes undefined to next step in promise chain
Promise.resolve('foo').then(val => {
Promise.reject(new Error('Bad Thing 4'));
}).then(val => {
console.log('LOG 4', val);
}).catch(err => {
console.error('ERR 4', err);
});
// Swallows Error Instance
// Passes undefined to next step in promise chain
Promise.resolve('foo').then(val => {
Promise.reject('Bad Thing 5');
}).then(val => {
console.log('LOG 5', val);
}).catch(err => {
console.error('ERR 5', err);
});
// Catches rejected Promise, but no Error is passed, only a String
Promise.resolve('foo').then(val => {
return Promise.reject('Bad Thing 6');
}).then(val => {
console.log('LOG 6', val);
}).catch(err => {
console.error('ERR 6', err);
});
//
// The right way to use Errors in Promises
//
// Throw an Error instance
Promise.resolve('foo').then(val => {
throw new Error('Bad Thing 7');
}).then(val => {
console.log('LOG 7', val);
}).catch(err => {
console.error('ERR 7', err);
});
// Return a rejected Promise contining an Error
Promise.resolve('foo').then(val => {
return Promise.reject(Error('Bad Thing 8'));
}).then(val => {
console.log('LOG 8', val);
}).catch(err => {
console.error('ERR 8', err);
});
// Return a rejected promise containing an Error
Promise.resolve('foo').then(val => {
return Promise.reject(new Error('Bad Thing 9'));
}).then(val => {
console.log('LOG 9', val);
}).catch(err => {
console.error('ERR 9', err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment