A lot of posts, questions and articles explain how to handle HTTP errors from fetch requests, but solutions only point logging
or just use text of the answer, but i'd like to get response details (status + statusText) and response text (given by the server)
I want to have a generic fetch_api
that I could use in my different components then. For the valid response it's working, but for the error I can't manage to get details + text from server, because I need to return a rejected Promise
but I can't make it working, here are my tries to get
- response.status
- response.statusText
- response.url
- response.text() // this is a Promise and I can't get it and also the details
static fetch_api(url, method = 'get') {
return fetch(url, {method: method})
.then(res => {
if (res.ok) return res.json();
throw res;
})
.then((result) => result
, (error) => {
const err = ("[" + error.status + ":" + error.statusText + "] while fetching " +
error.url + ", response is " + error.text()) // how to get server text
return Promise.reject(err) // ok but server text missing
//Er [404:NOT FOUND] while ... is [object Promise]
return Promise.reject().then(() => error.text()) // Not ok
return Promise.reject(error.status) // OK but need all
return Promise.reject(error.statusText) // OK but need all
}
)
}
// USE
fetchStatus() {
App.fetch_get(host + "/statusERROR")
.then(result => this.setState({isLoaded: true, modules: result}))
.catch(error => this.setState({isLoaded: true, error: {message: error}}))
}
Sources for basic handling, mots of them is just logging
- react native fetch http request throw error
- Fetch image in React from Node.js request
- https://github.com/github/fetch/issues/203
- https://gist.github.com/odewahn/5a5eeb23279eed6a80d7798fdb47fe91
- https://www.tjvantoll.com/2015/09/13/fetch-and-errors/
- https://gist.github.com/philipszdavido/fea2e353805294f374b6cb121ce43fa5