Try/Catch vs .catch() on Promises
You'll learn: When to use try/catch blocks versus .catch() methods for handling async errors, and how to choose the right approach for your situation.
Two Valid Error-Handling Styles
When working with promises in async functions, you have two legitimate approaches for error handling:
Try/catch blocks wrap your await expressions:
async function fetchUser(id) {
try {
const response = await fetch(`/users/${id}`);
const user = await response.json();
return user;
} catch (error) {
console.error('Failed to fetch user:', error);
return null;
}
}
The .catch() method handles promise rejections directly:
async function fetchUser(id) {
return fetch(`/users/${id}`)
.then(response => response.json())
.catch(error => {
console.error('Failed to fetch user:', error);
return null;
});
}
When to Prefer Each
Use try/catch when:
- You're already using
await(more readable and consistent) - You need to handle multiple awaits together
- You want cleanup logic in a
finallyblock - Your code feels like procedural steps
Use .catch() when:
- You're working with promise chains without
await - You want to handle errors at specific points in a chain
- You're mixing callback-style code with promises
- A single operation needs isolated error handling
Think of it like choosing between a safety net under a trapeze (try/catch wraps everything) versus individual safety harnesses (.catch() on specific promises).
Key Takeaway: Both try/catch and .catch() are valid; choose try/catch for await-heavy code and .catch() for promise chains or isolated error handling.