Last active
September 12, 2018 01:56
-
-
Save michaelrambeau/20f32c1fe05cb2812d9159b655e8bad0 to your computer and use it in GitHub Desktop.
Tricks about error handling and promises
This file contains 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
/* | |
Context: we have an API that throws an error (not wrapped in a Promise). | |
We want to catch that error at the upper level, without making fail the main function | |
that should end normally. | |
*/ | |
function apiRequest() { | |
throw new Error('Big Bug') | |
} | |
async function action() { | |
console.log('Action...'); | |
try { | |
return await apiCall() // we need to `await` here, otherwise the error will NOT be caught at this level! | |
} catch (err) { | |
console.log('Bug caught at the action level, OK!') | |
} | |
} | |
async function main() { | |
try { | |
console.log('Start'); | |
await action() | |
console.log('The end'); | |
} | |
catch (err) { | |
console.log('Main catch, TOO BAD!') | |
} | |
} | |
main() |
This file contains 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
/* | |
Simulate an API call... that fails! | |
*/ | |
function apiRequest() { | |
// return Promise.resolve('OK') | |
throw new Error('Big bug!') | |
} | |
/* | |
2 versions of the same "action" | |
*/ | |
function action1() { | |
return new Promise((resolve, reject) => { | |
apiRequest() | |
.then((response) => { | |
resolve(response); | |
}) | |
.catch((error) => { | |
reject(error); | |
}); | |
}); | |
} | |
/* | |
The compact version | |
*/ | |
async function action2() { | |
return apiRequest() // we don't need to `await` but we have to use `async` keyword when it's called from "then pattern" | |
} | |
/* | |
2 patterns for the main function: | |
- async await | |
- .then callback | |
It's almost the same... but `action2` has to be an `async` function if we use `then` callback | |
*/ | |
async function mainAsyncPattern() { | |
// Both action1 and action2 | |
try { | |
const result = await action2() | |
console.log('It works', result) | |
} catch (err) { | |
console.error('It failed', err.message) | |
} | |
} | |
function mainThenPattern() { | |
// We can use either action1 or action2 because action2 is defined as an async function | |
// if action2 is not an async function, it fails! | |
action2() | |
.then(console.log) | |
.catch(err => console.error('It failed', err.message) ) | |
} | |
// mainAsyncPattern() | |
mainThenPattern() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment