fetch error javascript code example

Example 1: how to handle fetch errors

function CheckError(response) {
  if (response.status >= 200 && response.status <= 299) {
    return response.json();
  } else {
    throw Error(response.statusText);
  }
}

// Now call the function inside fetch promise resolver
fetch(url)
  .then(CheckError)
  .then((jsonResponse) => {
  }).catch((error) => {
  });

Example 2: fetch api javascript

fetch('http://example.com/movies.json')
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    console.log(myJson);
  });

Example 3: javascript fetch api get

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

Example 4: error handling in fetch

fetch("/api/foo")  .then(response => {    if (!response.ok) { throw response }    return response.json()  //we only get here if there is no error  })  .then(json => {    doSomethingWithResult(json)  })  .catch(err => {    err.text().then(errorMessage => {      displayTheError(errorMessage)    })  })