Skip to content

fetch() calls often proceed without regard for !response.ok #12522

@michaelfig

Description

@michaelfig

Describe the bug

The Response object returned by the Fetch API needs to have its resp.ok value asserted to distinguish successful responses from error responses before other properties in the response can be used correctly.

To Reproduce

Steps to reproduce the behavior:

  1. `const json = await fetch(urlThatReturns404).then(resp => resp.json());
  2. See error: Uncaught SyntaxError: Unexpected token '<', "<!doctype "... is not valid JSON

Expected behavior

The 404 status should result in a rejection before parsing the JSON.

Platform Environment

  • what OS are you using? what version of Node.js? macOS, Node.js v22
  • is there anything special/unusual about your platform? no
  • what version of the Agoric-SDK are you using? ymax-v0.3.2602-beta3-41-g347a07c94a

Additional context

I would expect most fetch usage to be wrapped in something like:

const mustFetch = (...args) => fetch(...args).then(resp => {
  if (!resp.ok) throw Error(`Cannot fetch: ${fetch.status} ${fetch.statusText}`);
  return resp;
});

Screenshots

The search output (saved to fetchcalls.txt) of

find . \( -name xsnap -o -name dist -o -name bundles -o -name node_modules -o -name vendor \) -prune \
  -o -name '*.[tj]s' -print | sort | xargs rg -n -A2 '\bfetch\(' \
  | tee fetchcalls.txt | less

is illuminating.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions