[whatwg/fetch] Add Fetch Assertions (Issue #1683)

As an extension and counter to #1679 I propose adding fetch assertions.

## Example

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

## Reasoning
- Many languages/libraries regard 4xx & 5xx statuses as errors (error statuses)
- Many devs (esp inexperienced) assume `fetch()` throws under conditions in which it does not
- There is precedent for throwing under certain conditions (eg ` signal` or `integrity`)
- We can already assume errors based on the mismatch of the Accept & Content-Type headers (here the matching is `acceptable`)
- This potentially allows for arbitrary error conditions
- This is backwards compatible, though checking status and headers where not supported kinda defeats the purpose (where not supported, `assert` it's ignored and checks still have to be made, but it's a single thing to polyfill)
- It can be extended to include other assertions in a backwards-compatible way
- It allows for more meaningful errors
- It can close a connection early in the event that an assertion fails (a potential `maxContentLength` comes to mind, probably as an additional option)
- taking `integrity` as example (which is probably duplicated in functionality here), this provides additional error conditions where the response isn't what the dev expected
- It provides for a new type of error (maybe HTTPError or FetchAssertionError) without conflicting with current usage 
- In the case of `maxContentLength`, this could be used to avoid excessive data usage on slow/mobile connections
- In general, there are many ways in which we should know early that `fetch()` results in an error based solely on the response + headers but can't currently throw and close
- It does not preclude a new error type which has access to response status + headers + body, which may be important to certain errors (e.g. a 500 "Internal Server Error" that often responds with HTML instead of JSON and is the actually relevant error)

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

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

Received on Monday, 3 July 2023 03:08:31 UTC