Briefly
The catch
method is used to handle errors during the execution of an asynchronous operation.
The method takes one argument:
on
— a callback function that will be called when the promise transitions to the "error" stateReject rejected
. The function has one parameter that receives information about the error.
It returns a promise.
How it is written
// getPasswords() — an asynchronous function that returns a promisegetPasswords() .then(function (result) { // will execute if the operation is successful }) .catch(function (err) { // the callback will execute if getPassword finishes with an error alert(err.message) })
// getPasswords() — an asynchronous function that returns a promise getPasswords() .then(function (result) { // will execute if the operation is successful }) .catch(function (err) { // the callback will execute if getPassword finishes with an error alert(err.message) })
How to understand
catch
executes the provided callback when the asynchronous operation:
- calls the
reject
function inside the promise.( )
const rejectInSecond = new Promise(function (resolve, reject) { setTimeout(function () { reject(new Error('time is up')) }, 1000)})rejectInSecond.catch(function (err) { console.error(err.message) // 'time is up'})
const rejectInSecond = new Promise(function (resolve, reject) { setTimeout(function () { reject(new Error('time is up')) }, 1000) }) rejectInSecond.catch(function (err) { console.error(err.message) // 'time is up' })
- throws an error using
throw
.
const throwInSecond = new Promise(function (resolve, reject) { setTimeout(function () { throw new Error('time is up') }, 1000)})throwInSecond.catch(function (err) { console.error(err.message) // 'time is up'})
const throwInSecond = new Promise(function (resolve, reject) { setTimeout(function () { throw new Error('time is up') }, 1000) }) throwInSecond.catch(function (err) { console.error(err.message) // 'time is up' })
🔧 Technical detail
Under the hood, catch
contains a call to then
, where the first callback is set to undefined
: catch
→ then
.
In practice
Advice 1
🛠 Always complete your promise chains by calling the catch
method. If an error occurs in one of the operations in the chain and it is not handled, JavaScript will output the message Uncaught
in the developer console and will stop working on the entire page.