Skip to content

Instantly share code, notes, and snippets.

@thiagoh
Last active September 14, 2018 04:25
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 thiagoh/c4950b161074c1d95509ec4c02485ef3 to your computer and use it in GitHub Desktop.
Save thiagoh/c4950b161074c1d95509ec4c02485ef3 to your computer and use it in GitHub Desktop.
Promise Error Handling
## How to run
#
# npm run main /invalid
#
const get = url => {
if (url.indexOf('/invalid') >= 0) {
return Promise.reject({
url,
error: 'error message',
response: {
status: 400
}
});
}
return Promise.resolve({
url,
status: 200,
body: 'output'
});
};
const getSwallowerInterceptor = url => {
return get(url)
.then(output => {
console.log('GET then');
return output;
})
.catch(error => {
console.error('GET catch');
return error;
});
};
const getThrowerInterceptor = url => {
return get(url)
.then(output => {
console.log('GET then');
return output;
})
.catch(error => {
console.error('GET catch');
return Promise.reject(error);
});
};
const getNoCatchHandlingInterceptor = url => {
return get(url)
.then(output => {
console.log('GET then');
return output;
});
};
const urlParam = process.argv[2];
getSwallowerInterceptor(urlParam)
.then(response => console.log('GET[swallower] then', response))
.catch(error => console.error('GET[swallower] catch', error));
getThrowerInterceptor(urlParam)
.then(response => console.log('GET[thrower] then', response))
.catch(error => console.error('GET[thrower] catch', error));
getNoCatchHandlingInterceptor(urlParam)
.then(response => console.log('GET[noCatch] then', response))
.catch(error => console.error('GET[noCatch] catch', error));
/*
GET catch
GET catch
GET[swallower] then { url: '/invalid',
error: 'error message',
response: { status: 400 } }
GET[noCatch] catch { url: '/invalid',
error: 'error message',
response: { status: 400 } }
GET[thrower] catch { url: '/invalid',
error: 'error message',
response: { status: 400 } }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment