我有以下承诺链:
return fetch(request)
.then(checkStatus)
.then(response => response.json())
.then(json => ({ response: json }))
.catch(error => ({ error }))
checkstatus()
检查请求是否成功,如果不成功则返回错误。将捕获并返回此错误。但是,问题是我想将response.statusText
和response.json()
的结果都添加到错误中。问题在于,当我解析它时,我失去了链中的原始响应,因为我必须返回response.json()
,因为它是一个承诺。
这就是checkstatus目前所做的事情:
const checkStatus = response => {
if (response.ok) return response
const error = new Error('Response is not ok')
// this works because the response hasn't been parsed yet
if (response.statusText) error.message = response.statusText
// an error response from our api will include errors, but these are
// not available here since response.json() hasn't been called
if (response.errors) error.errors = response.errors
throw error
}
export default checkStatus
如何使用error.message = response.statusText
和error.errors = response.json().errors
返回错误?
答案 0 :(得分:2)
这是我的理解fetch
错误处理的帮手, fetchOk :
let fetchOk = (...args) => fetch(...args)
.then(res => res.ok ? res : res.json().then(data => {
throw Object.assign(new Error(data.error_message), {name: res.statusText});
}));
然后我替换fetch。
let fetchOk = (...args) => fetch(...args)
.then(res => res.ok ? res : res.json().then(data => {
throw Object.assign(new Error(data.error_message), {name: res.statusText});
}));
fetchOk("https://api.stackexchange.com/2.2/blah")
.then(response => response.json())
.catch(e => console.log(e)); // Bad Request: no method found with this name
var console = { log: msg => div.innerHTML += msg + "<br>" };
&#13;
<div id="div"></div>
&#13;
除非出现错误,否则不会加载数据,直接替换它。
答案 1 :(得分:1)
我使用新的async / await语法,因为它以更直观的方式读取:
async fetchData(request) {
try {
const response = await fetch(request)
const data = await response.json()
// return the data if the response was ok
if (response.ok) return { data }
// otherwise return an error with the error data
const error = new Error(response.statusText)
if (data.errors) error.errors = data.errors
throw error
} catch (error) {
return { error }
}
}
它可以很容易地处理fetch
返回的承诺以及response.json()
返回的承诺。