Catching errors with catch
Learn to catch a promise rejection and use the error message.
Catching errors with catch
When a promise rejects, you catch the error with the catch method. catch sits at the end of the chain and receives the rejection reason.
loadOrder()
.then(order => console.log(order))
.catch(error => console.log(error));A rejection flows down the chain; each then is skipped until a catch handles it. This lets you handle errors in one place and avoid repeated checks from callbacks.
catch enables recovery
catch is shorthand for then(null, onRejected); it handles only the failure case. After you catch an error, the value you return from catch creates a new fulfilled promise and the chain continues normally.
loadOrder()
.catch(error => 'default')
.then(order => console.log(order));This lets you recover from an error and continue the chain. You can show fallback data to the user this way.
Exercise Build a then and catch chain
A function called fetchPrice returns a promise. Call fetchPrice; in then log the price with console.log; add catch at the end of the chain and log the error with console.log.
Show example solution
fetchPrice()
.then(price => console.log(price))
.catch(error => console.log(error));
Test yourself
-
What parameter does catch take?
- The resolved value
- The promise object
- An array
- The rejection reason
Show answer
The rejection reason — Correct! catch receives the rejection reason.
-
Add catch to the chain
loadOrder() .then(order => console.log(order)) .____(error => console.log(error));Show answer
loadOrder() .then(order => console.log(order)) .catch(error => console.log(error)); -
Match catch concepts
- catch
- Catches a rejection
- then(null, fn)
- Same job as catch
- value from catch
- Creates a new fulfilled promise