JavaScript: .catch()
The .catch() method handles a rejected Promise so your code can report a useful failure instead of hiding it.
What you will learn
- How
.then()and.catch()separate success and failure - How to log errors safely and show a helpful message to users
- How
.catch()relates totry...catchandasync/await
Minimal example
fetch("data.json")
.then(response => response.json())
.then(data => {
console.log("Data loaded:", data);
})
.catch(error => {
console.error("Could not load data:", error);
});The .catch() callback runs when the Promise is rejected or when an earlier callback in the chain throws. Put the recovery or reporting logic there instead of leaving the failure invisible.
Common mistakes
- Do not leave the callback empty; an ignored failure is difficult to diagnose.
- Do not show raw error details or stack traces to users; log safely and show a clear message.
- Remember that
fetch()does not reject for an HTTP 404 or 500 by itself; checkresponse.okwhen needed.