Promise.prototype.catch()

Registers an error-handling function that runs when the promise is rejected.

Returns
A new promise, fulfilled with the handler’s result, or with the original value if there was no error.
On this page

Example

#
JavaScript
const loadCourse = (id) =>
  new Promise((resolve, reject) => {
    setTimeout(() => {
      if (id === 1) resolve({ id, title: 'HTML and CSS' })
      else reject(new Error(`No course with id ${id}`))
    }, 200)
  })

loadCourse(5)
  .then((course) => console.log(course.title))
  .catch((error) => console.log('Error:', error.message))
Console
Error: No course with id 5

Definition and usage

#

The catch() method takes a function that receives the reason the promise was rejected, usually an Error object. It works like then(undefined, onRejected), but is more readable and is usually placed at the end of the chain.

An error flows down the chain. If any earlier step rejects the promise or throws an exception, the remaining then() calls are skipped and control jumps to the nearest catch().

catch() also returns a new promise. When the handler function returns a value, the chain goes back to normal operation with that value, which lets you substitute fallback data. If you want to pass the error along, rethrow it with throw.

Syntax

#
Syntax
promise.catch(onRejected)

Parameters

#
  • onRejected

    function (reason)

    The function called with the rejection reason. Its result becomes the value of the new promise.

More examples

#
Fallback value after an error
JavaScript
const loadAvatar = () => Promise.reject(new Error('No connection'))

loadAvatar()
  .catch(() => 'default-avatar.png')
  .then((avatar) => console.log(avatar))
Console
default-avatar.png
An exception in then() also lands in catch()
JavaScript
Promise.resolve('{"level": 7')
  .then((text) => JSON.parse(text))
  .then((data) => console.log(data.level))
  .catch((error) => console.log(error.name))
Console
SyntaxError

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Put catch() at the end of the chain. It catches errors from every earlier step, including exceptions thrown inside then().
  • Don’t hide errors with an empty function. At least log them to the console, or show the user a message.
  • In code using await, a try...catch block gives you the same effect.

Related entries

#

Spotted a mistake or missing an example? Write to us.