Skip to content

Instantly share code, notes, and snippets.

@brandonweis
Created June 18, 2020 10:46
Show Gist options
  • Save brandonweis/fe32989f9848fecec46d3aea6976081c to your computer and use it in GitHub Desktop.
Save brandonweis/fe32989f9848fecec46d3aea6976081c to your computer and use it in GitHub Desktop.
// 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