Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I use the Fetch API to handle HTTP errors in JavaScript?
Asked on Feb 14, 2026
Answer
The Fetch API provides a modern way to make HTTP requests in JavaScript, but it doesn't automatically handle HTTP errors. You need to manually check the response status to handle errors effectively.
<!-- BEGIN COPY / PASTE -->
fetch("https://api.example.com/data")
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error("There was a problem with the fetch operation:", error);
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "fetch" function initiates a network request to the specified URL.
- The "response.ok" property checks if the HTTP status code is in the 200-299 range.
- If the response is not "ok", an error is thrown with the status code.
- The "catch" block handles any errors that occur during the fetch operation.
- Always ensure error handling is in place to manage network issues or server errors.
Recommended Links:
