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

Recovering from Errors with .catch()

Learn how .catch() can return a value to recover from an error and continue the Promise chain successfully.

Recovering from Errors with .catch()

You'll learn how .catch() can return a value to transform an error into a successful result, allowing the Promise chain to continue normally.

The Recovery Pattern

When .catch() handles an error, it doesn't have to end in failure. If your .catch() handler returns a value (instead of throwing or rejecting), that value becomes the resolved value for the next .then() in the chain. The error is effectively "caught and handled," and execution continues as if nothing went wrong.

Think of it like a safety net under a tightrope walker. If they fall (error occurs), the net catches them (.catch() runs), and they can climb back up and continue walking (chain continues with the recovery value).

How It Works

fetch('/api/user')
  .then(response => response.json())
  .catch(error => {
    console.log('API failed, using cached data');
    return { name: 'Guest', cached: true }; // Recovery value
  })
  .then(user => {
    console.log(user.name); // Works whether API succeeded or we used fallback
  });

Here, if the fetch fails, .catch() returns a fallback user object. The next .then() receives this fallback data and continues normally—it doesn't even know an error occurred upstream.

Common Recovery Scenarios

  • Default values: Return a sensible default when data can't be loaded
  • Cached data: Fall back to stored information
  • Graceful degradation: Return partial results instead of total failure
  • Retry values: Return a signal that lets the chain try an alternative approach

Key Takeaway: When .catch() returns a value, it converts failure back into success, allowing your Promise chain to recover gracefully and continue executing subsequent .then() handlers.