在现代浏览器/Node polyfill中,能否让Fetch的text()方法抛出异常?
Absolutely, there are scenarios where calling text() on a Fetch API Response will throw an exception—though these cases are distinct from the parsing failures that trigger errors with json(). Let’s break down the common scenarios:
Network or response stream interruptions: If the request is aborted mid-flight (e.g., the user closes the tab, network drops suddenly) or the response data gets corrupted during transmission,
text()won’t be able to read the complete response body. This will reject the Promise returned bytext()with an error.Response body already consumed: The Response object’s body is a one-time readable stream. If you’ve already called another body-parsing method like
json(),blob(), or even a previoustext()on the same Response instance, callingtext()again will throw an error—since the stream has already been used up.Here’s a quick example of this scenario:
fetch('https://example.com/some-data') .then(response => { // First, we consume the stream with json() response.json(); // Trying to read the same stream again with text() will fail return response.text(); }) .catch(error => { console.error("Error calling text():", error); // This will fire });CORS restrictions violations: If your request violates Cross-Origin Resource Sharing rules (e.g., requesting a resource from a different origin without proper server-side permissions), the browser may block access to the response body entirely. Calling
text()in this case will result in an exception.Invalid character encoding (rare): If the response claims to use a specific character encoding (like UTF-8) but the actual byte data doesn’t conform to that encoding, modern browsers might throw an error during decoding. That said, most browsers are designed to be lenient here, so this is a less common case.
To contrast with json(): json() throws errors when the response body is valid bytes but can’t be parsed into a JavaScript value. text()’s exceptions are almost always related to the ability to read or decode the raw response data, not the content of the string itself—even if the response is empty or contains garbage text, text() will still resolve to that string as long as it can read the stream successfully.
内容的提问来源于stack exchange,提问作者Dwight

