Re-throwing Errors After Partial Handling
You'll learn how to catch errors in async functions, perform some handling (like logging or transformation), then re-throw them so higher-level code can also respond.
Why Re-throw?
Sometimes you want to handle an error partially at one level—maybe log it, add context, or clean up resources—but you don't want to fully resolve the problem there. You need the error to continue propagating up the call stack so other parts of your application can react appropriately.
Think of it like a security checkpoint: you inspect the problem, take notes, but then pass it along to your supervisor who makes the final decision.
The Pattern
Inside a try/catch block in an async function, you catch the error, do whatever partial handling you need, then use throw to re-throw it:
async function fetchUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
return await response.json();
} catch (error) {
// Partial handling: log for debugging
console.error(`Failed to fetch user ${userId}:`, error.message);
// Re-throw so calling code can handle it too
throw error;
}
}
async function displayUser(userId) {
try {
const user = await fetchUserData(userId);
console.log(user.name);
} catch (error) {
// Higher-level handler shows user-friendly message
alert('Could not load user profile. Please try again.');
}
}
Here, fetchUserData logs the error for developers but re-throws it. The displayUser function then handles it by showing a user-facing message. Both levels get to respond appropriately.
You can also transform the error before re-throwing:
throw new Error(`User fetch failed: ${error.message}`);
Key Takeaway: Re-throwing errors with throw inside a catch block lets you handle errors at multiple levels—log, add context, or clean up locally, then propagate the error upward for higher-level handling.