很多帖子,问题和文章都解释了如何处理获取请求中的HTTP错误,但是解决方案仅指向logging
或仅使用答案的文本,但我想获取响应详细信息(status + statusText)和响应文本(给定)由服务器)
我想要一个通用的fetch_api
,然后可以在我的不同组件中使用。对于有效的响应,它是有效的,但是对于错误,我无法从服务器获取详细信息和文本,因为我需要返回rejected Promise
但无法使其正常工作,这是我尝试获得的信息
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}}))
}
基本处理的来源,它们的动机只是记录
最佳答案
终于明白了:使用res.text()
promise,并在i内部返回一个Promise.reject()
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+"]"))
)
}
像
App.fetch_get(host + "/status")
.then(result => this.setState({items: result}))
.catch(error => this.setState({error: error}}))
关于javascript - 如何从提取和 promise 中获取HTTP错误详细信息和文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58804084/