Kshlerin WebStudio πŸš€

Fetch reject promise and catch the error if status is not OK

September 19, 2026

πŸ“‚ Categories: Javascript
🏷 Tags: Redux Fetch-Api
Fetch reject promise and catch the error if status is not OK

Working with APIs in JavaScript often involves using the Fetch API, a powerful tool for making network requests. However, a common pitfall developers encounter is how to properly handle HTTP response statuses, particularly when the status is not “OK” (typically meaning not in the 200-299 range). The Fetch API, by default, doesn’t automatically reject the promise for non-200 status codes. This means you need to explicitly reject promise and catch the error if status is not OK to ensure your application handles errors gracefully. This article will delve into the best practices for handling Fetch API responses, demonstrating how to implement robust error handling and improve the reliability of your web applications. We’ll explore how to inspect the response status, throw errors when needed, and use try…catch blocks to manage potential failures, ensuring a smoother user experience and more stable code. Understanding how to handle errors effectively is crucial for any JavaScript developer using Fetch to interact with external APIs.

Understanding the Default Fetch Behavior

The Fetch API is designed to be flexible, but this flexibility comes with responsibility. Unlike older XMLHttpRequest methods, Fetch only rejects a promise when there’s a network error, such as the user being offline, or a DNS resolution failure. A server returning a 404 (Not Found) or a 500 (Internal Server Error) won’t automatically trigger a rejection. Instead, Fetch considers these as valid responses, albeit with error status codes. This behavior necessitates that developers manually check the response.ok property, which is a boolean indicating whether the HTTP response status code is in the 200-299 range. If response.ok is false, you need to manually throw an error to trigger the promise rejection, allowing you to handle the error in your catch block.

Failing to handle non-OK status codes can lead to unexpected behavior in your application. Imagine a scenario where your application requests user data from an API, and the API returns a 404 because the user doesn’t exist. If you don’t check the status code, your application might attempt to process the empty or error-filled response as valid data, leading to crashes or incorrect UI updates. Therefore, explicitly checking for response.ok is a crucial step in ensuring your application behaves predictably and reliably. Proper error handling prevents silent failures and provides a better user experience.

Consider the following example: you are building an e-commerce site and using Fetch to retrieve product details. If a product is out of stock (perhaps indicated by a 400 status code), without proper error handling, your application might try to display incomplete or incorrect information. This could lead to a frustrating experience for the user, who might think the product is available when it’s not. By implementing error handling, you can display a clear message indicating that the product is unavailable and prevent the application from crashing. This proactive approach is key to creating a professional and user-friendly web application. The Fetch API’s default behavior necessitates explicit checks for response.ok to ensure robust error handling and prevent application failures. Mozilla’s documentation on Fetch API further details these nuances.

Implementing Error Handling with Fetch

The key to effectively reject promise and catch the error if status is not OK with Fetch lies in checking the response.ok property and throwing an error when it’s false. This ensures that the promise rejects, allowing you to catch the error and handle it appropriately. This approach involves wrapping your Fetch call in a try…catch block. Within the try block, you make the Fetch request and check response.ok. If it’s false, you create a new Error object with a descriptive message and throw it. The catch block then catches this error, allowing you to log it, display an error message to the user, or take other appropriate actions. This strategy forms the foundation of robust error handling with the Fetch API.

Here’s a step-by-step guide to implementing error handling with Fetch:

  1. Make the Fetch request.
  2. Check response.ok.
  3. If response.ok is false, throw an error.
  4. Catch the error in a catch block.
  5. Handle the error appropriately.

For example:

async function fetchData(url) { try { const response = await fetch(url); if (!response.ok) { throw new Error(HTTP error! status: ${response.status}); } const data = await response.json(); return data; } catch (error) { console.error("Fetch error:", error); // Handle the error, e.g., display an error message to the user throw error; // Re-throw the error to propagate it if needed } } 

This code snippet demonstrates a robust approach to handling errors with the Fetch API. The fetchData function encapsulates the Fetch request within a try…catch block. The featured snippet-optimized paragraph is as follows: If the response.ok is false, the code throws an error with a message including the HTTP status, which is then caught in the catch block. This allows the developer to log the error, display a user-friendly message, or take other appropriate actions. Re-throwing the error ensures that the calling function can also handle the error if necessary, preventing unhandled exceptions. This ensures that errors are caught and handled gracefully, preventing unexpected behavior and providing a better user experience. You can also use async/await to simplify the asynchronous nature of Fetch. The fetchData function now uses async/await to make the code more readable and easier to understand. This approach makes it easier to manage asynchronous operations and handle errors in a synchronous-like manner.

Advanced Error Handling Techniques

Beyond basic error handling, there are several advanced techniques you can employ to make your Fetch error handling even more robust. One such technique is creating custom error classes that extend the built-in Error class. This allows you to define specific error types for different scenarios, making it easier to identify and handle errors based on their type. For example, you could create a NotFoundError class for 404 errors or a ServerError class for 500 errors. This provides a more granular approach to error handling, allowing you to tailor your response to specific error conditions.

Another advanced technique is using a retry mechanism for transient errors. Transient errors are temporary issues, such as network glitches or server overload, that might resolve themselves with a short delay. Implementing a retry mechanism involves automatically retrying the Fetch request a certain number of times with a delay between each attempt. This can improve the resilience of your application by automatically recovering from temporary errors. However, it’s important to implement retry mechanisms carefully to avoid overwhelming the server with repeated requests, especially in the case of persistent errors. You can use libraries like retry or implement your own custom retry logic.

Furthermore, consider implementing centralized error logging. By logging errors to a central location, you can gain valuable insights into the types of errors that are occurring in your application and identify patterns or trends. This can help you proactively address issues and improve the overall stability of your application. Centralized error logging can be achieved using services like Sentry or LogRocket, or by implementing your own custom logging solution. Effective error logging provides valuable data for debugging and improving application performance. According to a Sentry report, proactive error tracking can reduce user-reported bugs by up to 50%. Consider these points:

  • Use custom error classes for specific error types.
  • Implement a retry mechanism for transient errors.
  • Utilize centralized error logging for better insights.

Real-World Examples and Best Practices

Let’s consider a real-world example of using Fetch to retrieve data from a weather API. Imagine you’re building a weather application that displays current weather conditions for a given location. Your application makes a Fetch request to the weather API, but the API might return an error if the location is invalid or if there’s a problem with the API itself. By implementing proper error handling, you can ensure that your application gracefully handles these errors and provides a user-friendly experience.

Here’s how you can apply the error handling techniques we’ve discussed to this scenario:

async function getWeather(location) { try { const response = await fetch(https://api.example.com/weather?location=${location}); if (!response.ok) { if (response.status === 404) { throw new NotFoundError(Location "${location}" not found); } else { throw new ServerError(Weather API error: ${response.status}); } } const data = await response.json(); return data; } catch (error) { if (error instanceof NotFoundError) { console.error("Location not found:", error.message); // Display a message to the user indicating that the location is invalid } else if (error instanceof ServerError) { console.error("Weather API error:", error.message); // Display a message to the user indicating that the weather API is unavailable } else { console.error("Fetch error:", error); // Display a generic error message to the user } return null; // Or throw the error if you want to propagate it } } 

This example demonstrates how to use custom error classes and specific error handling logic to provide a more tailored response to different error conditions. By checking the response.status code, you can identify specific error types and handle them accordingly. This approach improves the user experience by providing more informative error messages. This ensures that errors are handled gracefully and provides a better user experience. Remember to replace https://api.example.com/weather with the actual API endpoint. Consider these best practices:

  • Always check response.ok to ensure the request was successful.
  • Use try…catch blocks to handle potential errors.
  • Provide informative error messages to the user.
Infographic here
By adhering to these best practices, you can create more robust and reliable web applications that gracefully handle errors and provide a better user experience. Remember that [effective error handling](https://courthousezoological.com/n7sqp6kh?key=e6dd02bc5dbf461b97a9da08df84d31c) is a crucial aspect of building professional-quality software.

FAQ

Why doesn't Fetch automatically reject the promise for non-200 status codes?
Fetch is designed to be flexible. It only rejects promises for network errors, not HTTP errors. This allows developers to handle different HTTP status codes in a more granular way.
What is the response.ok property?
The response.ok property is a boolean indicating whether the HTTP response status code is in the 200-299 range. If it's true, the request was successful; otherwise, it indicates an error.
How can I handle different types of errors with Fetch?
You can use custom error classes and check the response.status code to identify specific error types. This allows you to tailor your error handling logic based on the specific error condition.
By now, you should have a clear understanding of how to effectively manage errors when using the Fetch API in JavaScript. Remember to always check the response.ok property and use try...catch blocks to handle potential errors. Implementing these techniques will significantly improve the reliability and user experience of your web applications. Ready to take your Fetch error handling to the next level? Consider exploring advanced techniques like custom error classes and retry mechanisms. Dive deeper into the Fetch API documentation and start building more robust and resilient applications today! **Question & Answer :** Here's what I have going:
import 'whatwg-fetch'; function fetchVehicle(id) { return dispatch => { return dispatch({ type: 'FETCH_VEHICLE', payload: fetch(`http://swapi.co/api/vehicles/${id}/`) .then(status) .then(res => res.json()) .catch(error => { throw(error); }) }); }; } function status(res) { if (!res.ok) { return Promise.reject() } return res; } 

EDIT: The promise doesn’t get rejected, that’s what I’m trying to figure out.

I’m using this fetch polyfill in Redux with redux-promise-middleware.

Fetch promises only reject with a TypeError when a network error occurs. Since 4xx and 5xx responses aren’t network errors, there’s nothing to catch. You’ll need to throw an error yourself to use Promise#catch.

A fetch Response conveniently supplies an ok , which tells you whether the request succeeded. Something like this should do the trick:

fetch(url).then((response) => { if (response.ok) { return response.json(); } throw new Error('Something went wrong'); }) .then((responseJson) => { // Do something with the response }) .catch((error) => { console.log(error) });