Dwi*_*ght 5 javascript fetch-api
在现代浏览器中使用 fetch API(或节点 polyfill),是否可以生成一个场景,在该场景中在响应主体上调用 text() 可能会抛出异常?
对于不熟悉的人来说,调用 fetch 返回一个 Promise。然后可以在连续的 then() 回调中操作该 Promise。通常,我们将分别使用 .json() 或 .text() 函数将响应的正文转换为 JSON 或纯文本。
json() 函数可以简单地通过返回无法解析为 JSON 的内容来抛出异常。这样做将导致 .json() 以与 JSON.parse() 相同的方式抛出。但是,我一直无法找到 .text() 可以抛出的场景。
我对 Fetch Spec 的粗略检查没有揭示导致它抛出的方法,尽管它也没有提到 .json() 也可能抛出。
下面是一些说明该场景的示例代码:
const options = {
method: 'GET',
credentials: 'same-origin',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
};
fetch('/my-api-endpoint/', options)
.then((response) => {
// Assume we get here and fetch didn't fail before this point
return response.text();
})
.catch((e) => {
// How do we get here? Is it possible?
console.log('text() threw');
console.log(e);
}).then((text) => {
// We don't want to get here.
console.log(text);
});
Run Code Online (Sandbox Code Playgroud)
资源
没有起作用的事情:
'[object Object]'是否有可能导致 fetch 的 text() 函数抛出异常?
这是不可能的,因为text运行替换模式解码器;此外,您无法将解码器的错误模式fatal切换为。
yutakahirano在此评论中证实了这一点。
text可能会抛出