**.catch()** is syntactic sugar for `.then(null, onRejected)`. It handles any rejection from previous steps in the chain. After `.catch()` handles an error, the chain **continues** — unless you re-throw. Placing `.catch()` in the middle of a chain lets you recover from errors.
1Understanding .catch() Method
.catch() is syntactic sugar for .then(null, onRejected). It handles any rejection from previous steps in the chain. After .catch() handles an error, the chain continues — unless you re-throw. Placing .catch() in the middle of a chain lets you recover from errors.
A .catch() in the middle of a chain can recover and the chain continues. A .catch() at the end is a final fallback.
// .catch() provides a fallback
fetch('/api/preferences')
.then(r => r.json())
.catch(() => ({ theme: 'light', lang: 'en' })) // fallback defaults
.then(prefs => {
// prefs is either the fetched data OR the fallback
applyPreferences(prefs);
});2Practical Example
Here is a real-world application of .catch() Method showing how it is used in production JavaScript code.
// Multiple catch in a chain
Promise.resolve('start')
.then(v => { throw new Error('step1 failed'); })
.catch(e => {
console.log('Caught:', e.message);
return 'recovered'; // recovery value
})
.then(v => console.log('Chain continues with:', v));3Best Practices
Follow these guidelines when working with .catch() Method:
1. Always end Promise chains with .catch()
2. Re-throw in .catch() if you can't recover
3. Use .catch() in the middle to provide fallback values
Tip: A .catch() in the middle of a chain can recover and the chain continues. A .catch() at the end is a final fallback.
// .catch() provides a fallback
fetch('/api/preferences')
.then(r => r.json())
.catch(() => ({ theme: 'light', lang: 'en' })) // fallback defaults
.then(prefs => {
// prefs is either the fetched data OR the fallback
applyPreferences(prefs);
});