📖 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
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
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
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
Hint
Check your browser console or Node.js terminal to see the error message printed.
Practice
(1/5)
1. What is the main purpose of the .catch() method when working with JavaScript Promises?
easy
A. To create a new promise
B. To handle errors or rejected promises
C. To execute code after a promise resolves successfully
D. To cancel a running promise
Solution
Step 1: Understand the role of .catch() in Promises
The .catch() method is designed to handle errors or rejected promises in asynchronous code.
Step 2: Differentiate from other methods
.then() handles successful resolution, while .catch() specifically catches errors.
Final Answer:
To handle errors or rejected promises -> Option B
Quick Check:
.catch() handles errors [OK]
Hint: Remember: .catch() is for errors, .then() is for success [OK]
Common Mistakes:
Confusing .catch() with .then()
Thinking .catch() cancels promises
Believing .catch() creates new promises
2. Which of the following is the correct syntax to catch errors from a promise named myPromise?
easy
A. myPromise.catch(error => console.log(error));
B. myPromise.then(error => console.log(error));
C. myPromise.error(error => console.log(error));
D. myPromise.handleError(error => console.log(error));
Solution
Step 1: Identify the correct method for error handling
The correct method to catch errors from a promise is .catch().
Step 2: Check the syntax correctness
The syntax myPromise.catch(error => console.log(error)); correctly attaches an error handler.
Final Answer:
myPromise.catch(error => console.log(error)); -> Option A
Quick Check:
Use .catch() for errors [OK]
Hint: Use .catch() after promise to handle errors [OK]
Common Mistakes:
Using .then() to catch errors
Using non-existent methods like .error()
Incorrect arrow function syntax
3. What will be the output of the following code?
const p = new Promise((resolve, reject) => {
reject('Failed');
});
p.then(result => console.log('Success:', result))
.catch(error => console.log('Error:', error));
medium
A. Success: Failed
B. SyntaxError
C. No output
D. Error: Failed
Solution
Step 1: Analyze the promise rejection
The promise immediately rejects with the message 'Failed'.
Step 2: Trace the .then() and .catch() handlers
The .then() is skipped because the promise is rejected; .catch() runs and logs 'Error: Failed'.
Final Answer:
Error: Failed -> Option D
Quick Check:
Rejected promise triggers .catch() [OK]
Hint: Rejected promises skip .then() and go to .catch() [OK]
Common Mistakes:
Expecting .then() to run on rejection
Thinking no output occurs on rejection
Confusing reject with resolve
4. Identify the error in this code snippet and choose the correct fix:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log('Error:', error));
// What is wrong here?
medium
A. Should use .error() instead of .catch()
B. Missing return in first .then() to pass parsed JSON
C. No error, code is correct
D. fetch() does not return a promise
Solution
Step 1: Review the promise chain syntax
The code correctly chains .then() to parse JSON and then log data.
Step 2: Confirm error handling
The .catch() properly handles any errors from fetch or JSON parsing.
Final Answer:
No error, code is correct -> Option C
Quick Check:
Proper chaining with .catch() [OK]
Hint: fetch returns promise; .then() chaining is correct [OK]
Common Mistakes:
Thinking .then() needs explicit return (arrow with braces)
Using .error() instead of .catch()
Believing fetch is not promise-based
5. You want to handle errors in a promise chain but also continue processing even if an error occurs. Which pattern correctly achieves this?