Re: [whatwg/fetch] Consider response.throwIfNotOk() (Issue #1679)

I think that what I have in mind is better suited for its own issue upon thinking about it, but I do want to push back a little against some assumptions being made here:

- there are other reasons for `fetch()` to error (CORS, CSP `{redirect:'error'}`, an aborted signal, so it's not a given that `fetch()` is taking place outside of a `try`
- `fetch().then().catch()` should still be taken into consideration
- Not all responses will be JSON - it may be that an internal server error is HTML when the expected response is JSON (`resp.json()` would just throw a not-so-useful JSON parsing error there)

What I have in mind here would better fall under "Fetch Assertions". For the sake of addressing the issue at hand here, that'd be:

```js
try {
  const resp = await fetch(url, {
    headers: { Accept: 'application/json' },
    assert: { ok: true, acceptable: true },
    redirect: 'error',
    mode: 'cors',
    integrity: '... ',
    signal: AbortSignal.timeout(3000),
    /* ...*/
  });
  // Handle response knowing it's `ok` and JSON per the Accept/Content-Type headers
} catch (err) {
  // Handle error
}
```

I think that's the more versatile and useful approach. This would leave open any number of error conditions a dev could specify based on request and response headers. And with an additional option could close the connection early (maybe based on Content-Type or Content-Length).

I still think that the actual response body and headers will be highly relevant to many errors thrown, but let's treat that as a separate issue for now.

My proposal is adding fetch assertions, with status/statusRange/ok being among the options. If assertions are not met by the response headers/status, throw an error (whether or not that is a new type of error with response headers and body is a different question).

-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/fetch/issues/1679#issuecomment-1617111868
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/fetch/issues/1679/1617111868@github.com>

Received on Monday, 3 July 2023 02:04:40 UTC