Problem Statement
How do you handle errors in async await?
Explanation
In async await, you handle errors using try catch blocks.
Wrap the await statements inside a try block. If any promise rejects, execution jumps to the catch block.
You can also use catch on the promise returned by the async function.
Finally block runs regardless of success or failure, useful for cleanup.
Proper error handling prevents your application from crashing and provides better user experience.
Code Solution
SolutionRead Only
// Using try catch
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.log('Error:', error.message);
} finally {
console.log('Cleanup code runs always');
}
}
// Multiple awaits with error handling
async function getUser(id) {
try {
const user = await fetchUser(id);
const posts = await fetchPosts(user.id);
const comments = await fetchComments(posts[0].id);
return {user, posts, comments};
} catch (error) {
console.log('Failed to get user data:', error);
return null;
}
}
// Using .catch() on async function
fetchData().catch(error => {
console.log('Caught:', error);
});
// Handling specific errors
async function getData() {
try {
const response = await fetch('/api/data');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
if (error.name === 'TypeError') {
console.log('Network error');
} else {
console.log('Other error:', error);
}
throw error; // Re-throw if needed
}
}
// Without try catch (not recommended)
async function badExample() {
const data = await fetch('/api/data'); // Unhandled rejection!
return data;
}