0
0
Javascriptprogramming~30 mins

Error handling with async and await in Javascript - Mini Project: Build & Apply

Choose your learning style9 modes available
Error handling with async and await
📖 Scenario: You are building a simple web app that fetches user data from a server. Sometimes the server might fail or the data might not be available. You want to handle these errors gracefully so the app does not crash and shows a friendly message.
🎯 Goal: Learn how to use async and await to fetch data and handle errors using try and catch blocks in JavaScript.
📋 What You'll Learn
Create an async function to simulate fetching user data
Add a variable to simulate success or failure
Use try and catch inside the async function to handle errors
Print the result or error message
💡 Why This Matters
🌍 Real World
Handling errors when fetching data from servers is common in web apps to avoid crashes and show friendly messages.
💼 Career
Knowing async error handling is essential for frontend and backend developers working with APIs and asynchronous code.
Progress0 / 4 steps
1
Create an async function to fetch user data
Write an async function called fetchUserData that returns a resolved promise with the string 'User data loaded'.
Javascript
Need a hint?

Use the async keyword before the function name and return a string directly.

2
Add a variable to simulate success or failure
Inside the fetchUserData function, create a variable called success and set it to false to simulate a failure scenario.
Javascript
Need a hint?

Use const success = false; inside the function.

3
Use try and catch to handle errors
Modify the fetchUserData function to use a try block. Inside try, if success is false, throw a new Error with the message 'Failed to load user data'. Otherwise, return 'User data loaded'. Add a catch block that returns the error message.
Javascript
Need a hint?

Use try { if (!success) throw new Error(...); return ...; } catch (error) { return error.message; }

4
Call the async function and print the result
Write code to call fetchUserData() using await inside an async function called main. Then print the result using console.log. Finally, call the main function.
Javascript
Need a hint?

Wrap the call in an async main function, use await, then print the result.