JavaScriptAsyncBeginner

Promise.prototype.catch()

The `catch()` method of a Promise object schedules a function to be called when the promise is rejected, handling errors in an asynchronous operation.

Review the syntaxStudy the examplesOpen the coding app
promise.catch(onRejected);

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

The `catch()` method of a Promise object schedules a function to be called when the promise is rejected, handling errors in an asynchronous operation.

The `Promise.prototype.catch()` method is a fundamental part of error handling in JavaScript's asynchronous programming with Promises. It is essentially syntactic sugar for `promise.then(null, onRejected)`, providing a more readable and idiomatic way to register a callback function that will be executed only when the promise is rejected (i.e., when an error occurs). This method returns a new Promise, which allows for chaining multiple `catch()` blocks or further `then()` calls. If an error occurs within a `then()` callback, or if the original promise itself rejects, the control flow will jump to the nearest `catch()` handler down the chain. This mechanism ensures that errors in asynchronous operations are gracefully handled, preventing unhandled promise rejections that can lead to application crashes in Node.js or console warnings in browsers. It's crucial to always include a `catch()` block at the end of a promise chain to ensure all potential errors are caught, providing robust error management. The time complexity of `catch()` itself is negligible, as it merely schedules a callback; the actual error handling execution depends on when the promise rejects.

Quick reference

Syntax

promise.catch(onRejected);

Inputs

Parameters

onRejectedFunction · A function called when the Promise is rejected. It receives the rejection reason (error) as its argument.

See it in practice

Examples

1

Basic error handling with catch()

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    const success = Math.random() > 0.5;
    if (success) {
      resolve('Operation successful!');
    } else {
      reject(new Error('Operation failed!'));
    }
  }, 100);
});

myPromise
  .then(message => console.log(message))
  .catch(error => console.error('Caught an error:', error.message));
Output:
Operation successful! (if resolved) Caught an error: Operation failed! (if rejected)

This example demonstrates how `catch()` handles a rejected promise. If `myPromise` rejects, the `onRejected` callback inside `catch()` is executed, logging the error message.

2

Chaining catch() after a then() error

Promise.resolve(1)
  .then(value => {
    console.log('First then:', value);
    throw new Error('Error in first then!');
  })
  .then(value => {
    console.log('Second then (will not run):', value);
    return value * 2;
  })
  .catch(error => {
    console.error('Caught:', error.message);
    return 'Recovered!'; // Returns a resolved promise
  })
  .then(value => {
    console.log('After catch:', value);
  });
Output:
First then: 1 Caught: Error in first then! After catch: Recovered!

An error thrown within a `then()` block causes the promise chain to skip subsequent `then()` blocks and jump directly to the nearest `catch()`. The `catch()` block itself can return a value, resolving the promise it returns and allowing the chain to continue.

3

Multiple catch() blocks (less common, but possible)

Promise.reject(new Error('Initial failure'))
  .catch(err => {
    console.error('First catch:', err.message);
    // If we throw here, the next catch will handle it
    // throw new Error('Error from first catch');
    return 'Handled by first catch'; // This resolves the promise
  })
  .catch(err => {
    console.error('Second catch:', err.message);
  })
  .then(result => {
    console.log('Final result:', result);
  });
Output:
First catch: Initial failure Final result: Handled by first catch

While typically one `catch()` at the end is sufficient, multiple `catch()` blocks can exist. If a `catch()` handler itself throws an error, the next `catch()` in the chain will handle it. If it returns a value, the subsequent `then()` blocks will receive that value.

Debug faster

Common Errors

1

Unhandled Promise Rejection

Cause: A promise rejects, but there is no `catch()` handler (or `then(null, onRejected)`) in its chain to handle the error.

Fix: Always terminate promise chains with a `catch()` block to ensure all potential errors are handled. In Node.js, this can lead to process termination; in browsers, it's a console warning.

new Promise((_, reject) => reject(new Error('Oops!')))
  .then(value => console.log(value)); // No catch(), will lead to unhandled rejection

Runtime support

Compatibility

Node.jsAll modernES6+

Source: MDN Web Docs

Common questions

Frequently Asked Questions

The `catch()` method of a Promise object schedules a function to be called when the promise is rejected, handling errors in an asynchronous operation.

onRejected: A function called when the Promise is rejected. It receives the rejection reason (error) as its argument.

Unhandled Promise Rejection: Always terminate promise chains with a `catch()` block to ensure all potential errors are handled. In Node.js, this can lead to process termination; in browsers, it's a console warning.