是否有可能导致 fetch 的 text() 函数抛出?

Is it possible to cause a fetch's text() function to throw?

在现代浏览器(或 node polyfill)中使用 fetch API,是否可以生成在响应主体上调用 text() 可能抛出异常的场景?

对于不熟悉的人,将 fetch returns 称为 Promise。然后可以在顺序的 then() 回调中对该承诺进行操作。通常,人们会分别使用 .json() 或 .text() 函数将 Response 的正文转换为 JSON 或纯文本。

json() 函数可以简单地通过返回无法解析为 JSON 的内容来抛出异常。这样做会导致 .json() 以与 JSON.parse() 相同的方式抛出。但是,我一直找不到 .text() 可以抛出的场景。

我对 Fetch 规范的粗略检查没有揭示导致它抛出的方法,尽管它也没有提到 .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);
    });

资源

无效的事情:

Is it possible to cause a fetch's text() function to throw?

不可能,因为text运行一个replacement mode decoder; furthermore you cannot switch the error mode解码器到fatal

yutakahirano confirms it in this comment.

text 可能会抛出

  • 如果它的请求在完成和消费之间中止
  • 如果 Content-Encoding 响应 header 与相应的 entity-body
  • 不匹配