Error Propagation with Async/Await
You'll learn how errors bubble up through async/await functions and how try/catch seamlessly handles promise rejections.
The Core Idea
When you use async/await, JavaScript transforms promise rejections into throwable errors. This means errors propagate up the call stack just like synchronous errors, and try/catch blocks work exactly as you'd expect. If an awaited promise rejects, it throws an error at that exact line—no special .catch() needed.
How It Works
Inside an async function, any error thrown (or any rejected promise you await) can be caught with try/catch. If you don't catch it, the error propagates to the calling function. Since async functions always return promises, an uncaught error becomes a rejected promise that the caller must handle.
async function fetchUser(id) {
if (id < 0) throw new Error('Invalid ID');
return { id, name: 'Alice' };
}
async function displayUser(id) {
try {
const user = await fetchUser(id);
console.log(user.name);
} catch (error) {
console.error('Display failed:', error.message);
}
}
displayUser(-1); // Logs: Display failed: Invalid ID
If displayUser didn't catch the error, it would propagate:
async function displayUser(id) {
const user = await fetchUser(id); // Error propagates up
console.log(user.name);
}
displayUser(-1).catch(err => {
console.error('Caught at top level:', err.message);
});
The Analogy
Think of async/await as a translator: it converts promise rejections (a message in "Promise language") into thrown errors (a message in "try/catch language"), so everything speaks the same error-handling dialect.
Key Takeaway: With async/await, promise rejections become throwable errors, making error propagation consistent with synchronous code and allowing try/catch to handle everything uniformly.