Created
June 18, 2020 10:46
-
-
Save brandonweis/fe32989f9848fecec46d3aea6976081c to your computer and use it in GitHub Desktop.
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
// promise error handling | |
function fetchAndUpdatePosts() { | |
fetchPosts() | |
.then((posts) => { | |
updatePosts(posts) | |
.catch((err) => { | |
console.log('error in updating posts'); | |
}); | |
}) | |
.catch(() => { | |
console.log('error in fetching posts'); | |
}); | |
} | |
// async/await error handling | |
async function fetchAndUpdatePosts() { | |
let posts; | |
try { | |
posts = await fetchPosts(); | |
} catch { | |
console.log('error in fetching posts'); | |
} | |
if (!posts) { | |
return; | |
} | |
try { | |
await updatePosts(); | |
} catch { | |
console.log('error in updating posts'); | |
} | |
// cleaner way but generic error handling | |
async function fetchAndUpdatePosts() { | |
let posts; | |
try { | |
posts = await fetchPosts(); | |
doSomethingWithPosts(posts); // throws an error | |
} catch { | |
// Now it handles errors from fetchPosts and doSomthingWithPosts. | |
console.log('error in fetching posts'); | |
} | |
} | |
// specific error handling | |
async function fetchAndUpdatePosts() { | |
const posts = await fetchPosts().catch(() => { | |
console.log('error in fetching posts'); | |
}); | |
if (posts) { | |
doSomethingWithPosts(posts).catch(() => { | |
console.log('error in do something with posts'); | |
}); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment