js error handling fetch 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: 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) }) })