catch()
ES6+Attaches a rejection handler callback to the promise.
Syntax
promise.catch(onRejected)Parameters
onRejected Function A function called when the Promise is rejected
Return Value
Promise
A new Promise
Examples
JavaScript
Promise.reject(new Error('실패!'))
.catch(error => {
console.log(error.message);
}); Output:
// '실패!'
📌 When to Use
Use catch() at the end of promise chains to handle errors, provide fallback values, or log failures gracefully.
⚠️ Common Mistakes
Placing catch() before then() calls that might throw, leaving errors unhandled.
Swallowing errors by not re-throwing or logging them.
✅ Best Practices
Catch can recover errors by returning a value, which continues the chain successfully.
Log errors and re-throw if you cannot handle them: catch(e => { log(e); throw e; }).
⚡ Performance Notes
catch() is essentially then(undefined, onRejected). There is no performance difference. Position catch() strategically based on error handling needs.
🌍 Real World Example
Resilient API Client
Handle API errors gracefully with fallback data and user-friendly messages.
function fetchUserProfile(userId) {
return fetch(`/api/users/${userId}`)
.then(response => {
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
})
.catch(error => {
console.error('Failed to fetch user:', error.message);
// Return fallback data
return {
id: userId,
name: 'Unknown User',
avatar: '/default-avatar.png',
error: true
};
});
}
// Usage - always returns data, even on failure
fetchUserProfile(999).then(user => {
console.log(user.name); // "Unknown User" if failed
});