0
0
Javascriptprogramming~15 mins

Promise error handling in Javascript - Mini Project: Build & Apply

Choose your learning style9 modes available
Promise error handling
📖 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 handle errors in JavaScript Promises using catch to keep your app safe and user-friendly.
📋 What You'll Learn
Create a Promise that simulates fetching user data
Add a variable to control if the fetch should fail or succeed
Use then to handle success and catch to handle errors
Print the result or error message to the console
💡 Why This Matters
🌍 Real World
Web apps often fetch data from servers that might fail. Handling errors with Promises keeps apps working smoothly and users informed.
💼 Career
Understanding Promise error handling is essential for frontend and backend JavaScript developers to build reliable applications.
Progress0 / 4 steps
1
Create a Promise to fetch user data
Create a Promise called fetchUser that after 1 second resolves with the string 'User data loaded'.
Javascript
Need a hint?

Use new Promise with resolve inside setTimeout to simulate delay.

2
Add a variable to control success or failure
Add a variable called shouldFail and set it to true. Update the fetchUser Promise so that if shouldFail is true, it rejects with the string 'Failed to load user data', otherwise it resolves with 'User data loaded'.
Javascript
Need a hint?

Use an if statement inside setTimeout to decide between resolve and reject.

3
Handle success and error with then and catch
Use fetchUser.then with a function that takes data and logs it with console.log. Then chain catch with a function that takes error and logs it with console.log.
Javascript
Need a hint?

Use then to handle success and catch to handle errors.

4
Print the final output
Run the code and observe the console output. It should print Failed to load user data because shouldFail is true. Write a console.log statement inside both then and catch to show the messages.
Javascript
Need a hint?

Check your browser console or Node.js terminal to see the error message printed.