javascript fetch error handling code example
Example 1: try catch 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 => {
this.props.dispatch(doSomethingWithResult(json))
})
.catch( err => {
err.text().then( errorMessage => {
this.props.dispatch(displayTheError(errorMessage))
})
})
Example 2: 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 3: 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);
}
Example 4: fetch error handling js
export async function getStaticProps(context) {
const res = await fetch(`https://...`)
const data = await res.json()
//use this statement for the program not to crush but go back to the home page
if (!data) {
return {
redirect: {
destination: '/',
permanent: false,
},
}
}
return {
props: {}, // will be passed to the page component as props
}
}