handle fetch errors post 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: how to handle fetch errors

const response = await fetch(url);
if (response.status >= 200 && response.status <= 299) {
  const jsonResponse = await response.json();
  console.log(jsonResponse);
} else {
  // Handle errors
  console.log(response.status, response.statusText);
}