fetch catch error javascript code example
Example 1: try catch fetch
fetch("/api/foo")
.then( response => {
if (!response.ok) { throw response }
return response.json()
})
.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);
}
}
fetch(url)
.then(CheckError)
.then((jsonResponse) => {
}).catch((error) => {
});
Example 3: fetch catch
fetch(url).then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error('Something went wrong');
}
})
.then((responseJson) => {
})
.catch((error) => {
console.log(error)
});