how to send error to fetch so it can catch error code example
Example 1: 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
}
}
Example 2: 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) }) })