Basic Try/Catch Pattern with Await
You'll learn how to wrap await expressions in try/catch blocks to handle errors from rejected promises gracefully.
The Fundamental Pattern
Now that you know await can throw when a promise rejects, you need a way to handle those errors. The most common pattern is wrapping your await expressions in a try/catch block:
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
return data;
} catch (error) {
console.error('Failed to fetch user:', error);
return null; // Provide a fallback value
}
}
How It Works
When a promise you're await-ing rejects, JavaScript treats it like a thrown error. The catch block intercepts it, giving you a chance to:
- Log the error for debugging
- Return a fallback value
- Clean up resources
- Re-throw the error if needed
Think of it like a safety net: without try/catch, the error would propagate up to the caller. With it, you catch and handle the problem right where it happens.
The Basic Structure
async function doSomething() {
try {
// All your await expressions go here
const result = await someAsyncOperation();
const nextResult = await anotherOperation(result);
return nextResult;
} catch (error) {
// Handle any error from any await above
console.error('Operation failed:', error);
}
}
A single catch block handles errors from all await expressions in the try block, making error handling much cleaner than chaining multiple .catch() calls.
Key Takeaway: Wrap await expressions in try/catch blocks to handle rejected promises as synchronous-looking errors, with the catch block intercepting failures from any awaited operation.