Last active
September 14, 2018 04:25
-
-
Save thiagoh/c4950b161074c1d95509ec4c02485ef3 to your computer and use it in GitHub Desktop.
Promise Error Handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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