Course contentsShow
← JavaScript
Lesson 1324 of 2,72329. PromisesFree lesson

Re-throwing Errors for Further Handling

When and how to throw from a catch block to propagate errors up to a higher-level handler.

Re-throwing Errors for Further Handling

What you'll learn: How to use throw inside a .catch() block to pass errors up the chain for higher-level error handling.

The Core Idea

Sometimes your .catch() block can't fully handle an error—maybe it can only log it, or maybe certain errors need special treatment elsewhere. In these cases, you can re-throw the error (or throw a new one) to propagate it up to the next .catch() in the chain or to an outer error handler.

When you throw inside a .catch(), the promise returned by that .catch() becomes rejected with the thrown error, allowing subsequent .catch() blocks to handle it.

When to Re-throw

Re-throw when you:

  • Can only partially handle the error (like logging)
  • Want to add context before passing it up
  • Need different handlers for different error types
  • Must ensure critical errors aren't silently swallowed

How It Works

fetchUserData()
  .then(user => processUser(user))
  .catch(err => {
    console.error('Error occurred:', err.message); // Log it
    throw err; // Re-throw for higher-level handling
  })
  .catch(err => {
    // This catch receives the re-thrown error
    alert('Something went wrong. Please try again.');
  });

You can also throw a different error:

fetchData()
  .catch(err => {
    if (err.status === 404) {
      throw new Error('Resource not found - check your ID');
    }
    throw err; // Re-throw other errors unchanged
  })
  .catch(err => {
    // Handle the transformed or original error
    displayErrorToUser(err.message);
  });

Think of it like a relay race: your .catch() handles the baton briefly (logs, inspects, transforms) then passes it to the next runner rather than stopping the race entirely.

Key Takeaway: Re-throwing errors from .catch() blocks lets you perform intermediate error handling (like logging or transformation) while still propagating the error to higher-level handlers that can take final action.