Fetch and HTTP Requests

When using the fetch function to make HTTP requests in JavaScript, it is important to handle errors properly to ensure that your application doesn't break. Here are a few ways you can handle errors when using fetch:

  1. Check the HTTP status code: You can check the status code of the Response object to see if the request was successful or not. For example, you can check if the status code is 200 OK or if it is in the 4xx or 5xx range to indicate an error.

  2. Use the ok property: The Response object has an ok property that is true if the status code is in the 200 range, and false otherwise. You can use this property to check if the request was successful or not.

  3. Use try and catch: You can use a try block to wrap your fetch call, and a catch block to handle any errors that occur. For example:

try {
  const response = await fetch('https://6away.org/data.json');
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}

4. Check the networkError property: If you are using the react-fetch library, you can check the networkError property of the response object to see if there was a network error.

Last updated