handle fetch error 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);
}
}
fetch(url)
.then(CheckError)
.then((jsonResponse) => {
}).catch((error) => {
});
Example 2: fetch error handling js
export async function getStaticProps(context) {
const res = await fetch(`https://...`)
const data = await res.json()
if (!data) {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}
return {
props: {},
}
}