Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Error handling in async/await
📖 Scenario: You are building a simple Node.js app that fetches user data from a fake API. Sometimes the API might fail, so you need to handle errors properly to keep your app running smoothly.
🎯 Goal: Learn how to use async functions with await and handle errors using try/catch blocks in Node.js.
📋 What You'll Learn
Create an async function to fetch user data
Add a helper variable to simulate API success or failure
Use try/catch to handle errors inside the async function
Call the async function and handle the final result or error
💡 Why This Matters
🌍 Real World
Handling errors in async/await is essential when working with APIs or any asynchronous operations in Node.js to keep applications stable and user-friendly.
💼 Career
Understanding async error handling is a key skill for backend developers, API developers, and anyone working with asynchronous JavaScript in Node.js environments.
Progress0 / 4 steps
1
Create the async function to fetch user data
Write an async function called fetchUserData that returns a promise resolving to the object { id: 1, name: 'Alice' }.
Node.js
Hint
Use the async keyword before the function and return the user object directly.
2
Add a helper variable to simulate API success or failure
Create a variable called apiSuccess and set it to false to simulate an API failure.
Node.js
Hint
Use const apiSuccess = false; to create the helper variable.
3
Use try/catch inside the async function to handle errors
Modify the fetchUserData function to use a try/catch block. Inside try, if apiSuccess is false, throw an error with the message 'API request failed'. Otherwise, return the user object { id: 1, name: 'Alice' }. In catch, rethrow the error.
Node.js
Hint
Use try to check apiSuccess. Throw an error if false. Catch the error and rethrow it.
4
Call the async function and handle the result or error
Write an async function called main that calls fetchUserData using await inside a try/catch block. In try, assign the result to a variable user. In catch, assign the error message to a variable errorMessage. Then call main().
Node.js
Hint
Use async function main() with try/catch. Await fetchUserData(). Handle error message in catch. Call main() at the end.
Practice
(1/5)
1. What is the main purpose of using try/catch blocks with async/await in Node.js?
easy
A. To catch and handle errors from asynchronous operations
B. To speed up the execution of async functions
C. To convert async functions into synchronous ones
D. To automatically retry failed async operations
Solution
Step 1: Understand async/await behavior
Async functions return promises and can throw errors when awaited operations fail.
Step 2: Role of try/catch
Try/catch blocks catch these errors to prevent crashes and allow handling.
Final Answer:
To catch and handle errors from asynchronous operations -> Option A
Quick Check:
Error handling = A [OK]
Hint: Use try/catch around await to catch errors [OK]
Common Mistakes:
Thinking async/await automatically handles errors
Using try/catch outside async functions only
Ignoring errors causing app crashes
2. Which of the following is the correct syntax to handle errors in an async function using async/await?
easy
A. async function fetchData() { try { await fetch(url); } catch (err) { console.error(err); } }
B. async function fetchData() { await fetch(url); }
C. async function fetchData() { try { fetch(url); } catch (err) { console.error(err); } }
D. async function fetchData() { await fetch(url).catch(console.error); }
Solution
Step 1: Check proper use of try/catch with await
async function fetchData() { try { await fetch(url); } catch (err) { console.error(err); } } correctly wraps the await call inside try and catches errors.
Step 2: Identify incorrect patterns
async function fetchData() { await fetch(url).catch(console.error); } uses .catch on await which is invalid syntax; async function fetchData() { try { fetch(url); } catch (err) { console.error(err); } } misses await; async function fetchData() { await fetch(url); } has no error handling.
Final Answer:
async function fetchData() { try { await fetch(url); } catch (err) { console.error(err); } } -> Option A
Quick Check:
Try/catch with await = D [OK]
Hint: Put await inside try block to catch errors [OK]
What will be logged if the fetch fails due to network error?
medium
A. An unhandled promise rejection error
B. The raw error object
C. Undefined
D. 'Error occurred'
Solution
Step 1: Analyze try/catch behavior on fetch failure
If fetch fails, control jumps to catch block which returns 'Error occurred'.
Step 2: Understand promise resolution
getData returns a resolved promise with string 'Error occurred', so console.log prints that string.
Final Answer:
'Error occurred' -> Option D
Quick Check:
Catch returns string on error = B [OK]
Hint: Catch block return value is logged on error [OK]
Common Mistakes:
Expecting unhandled error instead of caught return
Confusing error object with returned string
Ignoring async function returns promise
4. Identify the error in this async function:
async function loadUser() {
try {
const user = fetch('https://api.example.com/user');
console.log(user.name);
} catch (err) {
console.error(err);
}
}
medium
A. Incorrect catch block syntax
B. Missing await before fetch causing user to be a Promise
C. console.log should be inside catch block
D. fetch URL is invalid
Solution
Step 1: Check fetch usage
fetch returns a Promise; without await, user is a Promise object, not the resolved data.
Step 2: Consequence of missing await
Accessing user.name fails because user is not the actual data but a Promise.
Final Answer:
Missing await before fetch causing user to be a Promise -> Option B
Quick Check:
Await missing = A [OK]
Hint: Always await fetch to get resolved data before use [OK]
Common Mistakes:
Forgetting await before async calls
Assuming fetch returns data directly
Misplacing console.log outside async flow
5. You want to fetch user data and then fetch posts by that user. Both calls can fail. How should you handle errors to ensure you catch failures in either step and log a clear message?
async function getUserPosts(userId) {
// Your code here
}
hard
A. Use nested try/catch blocks: one for user fetch, one for posts fetch
B. Use .then().catch() chaining instead of async/await
C. Use a single try/catch wrapping both awaits for user and posts fetch
D. Ignore errors and let them crash the app
Solution
Step 1: Understand error flow in async/await
A single try/catch can catch errors from any awaited call inside it.
Step 2: Simplify error handling
Wrapping both awaits in one try/catch logs errors clearly without nesting complexity.
Final Answer:
Use a single try/catch wrapping both awaits for user and posts fetch -> Option C
Quick Check:
One try/catch covers multiple awaits = C [OK]
Hint: Wrap all awaits in one try/catch for simple error handling [OK]