Async/await helps write code that waits for tasks to finish. Handling errors properly keeps your program safe and clear.
Async/await error handling patterns in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
try { const result = await asyncFunction(); // use result } catch (error) { // handle error }
Use try to run code that might fail.
Use catch to handle any errors from the await call.
Examples
Node.js
async function fetchData() { try { const data = await fetch('https://api.example.com/data'); const json = await data.json(); console.log(json); } catch (error) { console.error('Error fetching data:', error); } }
Node.js
import fs from 'fs/promises'; async function readFile() { try { const content = await fs.readFile('file.txt', 'utf-8'); console.log(content); } catch (error) { console.error('Failed to read file:', error); } }
Node.js
async function processTasks() { try { const result1 = await task1(); const result2 = await task2(); console.log(result1, result2); } catch (error) { console.error('One of the tasks failed:', error); } }
Sample Program
This program tries to read a JSON config file asynchronously. If the file is missing or contains invalid JSON, it catches the error and prints a clear message.
Node.js
import fs from 'fs/promises'; async function readConfig() { try { const data = await fs.readFile('config.json', 'utf-8'); const config = JSON.parse(data); console.log('Config loaded:', config); } catch (error) { console.error('Error loading config:', error.message); } } readConfig();
Important Notes
Always use try/catch around await to avoid unhandled promise rejections.
You can also use Promise.allSettled() for multiple async calls to handle errors individually.
Logging error messages helps find problems quickly.
Summary
Use try/catch blocks to handle errors with async/await.
This makes async code easier to read and safer.
Always catch errors to prevent your program from crashing unexpectedly.
Practice
1. What is the main purpose of using
try/catch blocks with async/await in Node.js?easy
Solution
Step 1: Understand async/await behavior
Async/await pauses code execution until a promise settles, but errors can still happen.Step 2: Role of try/catch
Try/catch blocks catch errors thrown inside async functions to prevent crashes.Final Answer:
To handle errors that occur during asynchronous operations -> Option AQuick Check:
Error handling = D [OK]
Hint: Use try/catch to catch async errors safely [OK]
Common Mistakes:
- Thinking try/catch makes code faster
- Believing async/await removes need for error handling
- Assuming errors auto-retry without code
2. Which of the following is the correct syntax to catch errors in an async function using async/await?
easy
Solution
Step 1: Identify proper try/catch block usage
Try/catch must wrap the await expression inside the async function body.Step 2: Check syntax correctness
async function fetchData() { try { await fetch(); } catch (e) { console.error(e); } } correctly places try before await and catch after the block.Final Answer:
async function fetchData() { try { await fetch(); } catch (e) { console.error(e); } } -> Option CQuick Check:
Correct try/catch syntax = C [OK]
Hint: Wrap await inside try block, catch errors after [OK]
Common Mistakes:
- Placing catch outside function body
- Using .catch() on await directly
- Using try without braces
3. What will be logged to the console when running this code?
async function test() {
try {
await Promise.reject('fail');
} catch (error) {
console.log('Caught:', error);
}
}
test();medium
Solution
Step 1: Understand Promise.reject inside try block
The rejected promise throws an error caught by the catch block.Step 2: Check console.log output
The catch block logs 'Caught:' followed by the error message 'fail'.Final Answer:
Caught: fail -> Option BQuick Check:
Error caught and logged = B [OK]
Hint: Rejected promises inside try are caught by catch [OK]
Common Mistakes:
- Expecting unhandled rejection error
- Thinking error is logged without 'Caught:' prefix
- Assuming no output because of rejection
4. Identify the error in this async function error handling code:
async function load() {
try {
const data = await fetchData();
} catch {
console.error(error);
}
}medium
Solution
Step 1: Check catch block syntax
The catch block is missing the error parameter to receive the thrown error.Step 2: Understand console.error usage
console.error(error) references a variable 'error' which is undefined without catch parameter.Final Answer:
Missing error parameter in catch block -> Option DQuick Check:
Catch needs error param = A [OK]
Hint: Always name error in catch(e) to use it inside [OK]
Common Mistakes:
- Omitting error parameter in catch
- Misplacing await outside try
- Misusing console.error syntax
5. You want to run multiple async tasks in parallel and handle errors individually without stopping all tasks. Which pattern correctly handles errors for each async call using async/await?
hard
Solution
Step 1: Understand parallel async calls and error handling
Promise.all stops on first rejection; one try/catch around it catches all or none.Step 2: Individual error handling requires separate try/catch
Wrapping each await in its own try/catch lets errors be handled separately without stopping others.Final Answer:
Wrap each await call inside its own try/catch block -> Option AQuick Check:
Individual error handling = A [OK]
Hint: Try/catch each await separately for independent error handling [OK]
Common Mistakes:
- Using Promise.all with one try/catch stops all on first error
- Using forEach with await causes unexpected behavior
- Ignoring errors leads to crashes or silent failures
