-2

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

azro
  • 53,056
  • 7
  • 34
  • 70

1 Answers1

3

Finally got it : use the res.text() promise, and return a Promise.reject() inside of i

static fetch_api(url, method = 'get') {
    return fetch(url, {method: method})
        .then(res => {
            if (res.ok) return res.json();
            throw res;
        })
        .then(result => result)
        .catch(error => error.text().then(errormsg => Promise.reject("[" + error.status + ":" +
            error.statusText + "] while fetching " + error.url + ", response is [" + errormsg+"]"))
        )
}

To be used like

App.fetch_get(host + "/status")
    .then(result => this.setState({items: result}))
    .catch(error => this.setState({error: error}}))
azro
  • 53,056
  • 7
  • 34
  • 70