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.
Example
#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))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
#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
#const loadAvatar = () => Promise.reject(new Error('No connection'))
loadAvatar()
.catch(() => 'default-avatar.png')
.then((avatar) => console.log(avatar))Promise.resolve('{"level": 7')
.then((text) => JSON.parse(text))
.then((data) => console.log(data.level))
.catch((error) => console.log(error.name))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 insidethen(). - 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, atry...catchblock gives you the same effect.
Related entries
#- Promise.prototype.then()Registers a function to run when the promise is fulfilled, and returns a new promise so you can chain steps together.
- Promise.prototype.finally()Registers a function that runs once the promise settles, whether it ends in success or failure.
- try...catchCatches errors thrown in the try block and handles them in catch. The optional finally always runs.
- PromiseAn object representing the result of an operation that will be available in the future: a value on success or an error.
- throwThrows an exception: stops the current code and passes the error to the nearest catch block.
Spotted a mistake or missing an example? Write to us.