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:
Check the HTTP status code: You can check the status code of the
Responseobject to see if the request was successful or not. For example, you can check if the status code is200 OKor if it is in the4xxor5xxrange to indicate an error.Use the
okproperty: TheResponseobject has anokproperty that istrueif the status code is in the200range, andfalseotherwise. You can use this property to check if the request was successful or not.Use
tryandcatch: You can use atryblock to wrap yourfetchcall, and acatchblock 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