Skip to content

Error when fetching endpoint that's not json #1883

Closed
@newholder

Description

@newholder

Description

When fetching an endpoint that returns other than json and you forget to set parseAs and the endpoint return OK, it will throw an error.

If i'm not mistaken, this code govern how result are parsed

// parse response (falling back to .text() when necessary)
    if (response.ok) {
      // if "stream", skip parsing entirely
      if (parseAs === "stream") {
        return { data: response.body, response };
      }
      return { data: await response[parseAs](), response };
    }

    // handle errors
    let error = await response.text();
    try {
      error = JSON.parse(error); // attempt to parse as JSON
    } catch {
      // noop
    }
    return { error, response };

this line

 if (response.ok) {
      // if "stream", skip parsing entirely
      if (parseAs === "stream") {
        return { data: response.body, response };
      }
      return { data: await response[parseAs](), response };
    }

checks if fetch result are ok, and if it is, check if parseAs set to stream, skip parsing and return the body. If it isn't stream you parse it by calling the built-in function with the same name as parseAs and it defaulted to json. This could fail, and i think this exception is uncaught. Is this expected behaviour?

Reproduction

Create an openapi endpoint that return text, create client similar to getting started tutorial and try to fetch that endpoint without setting parseAs

Expected result

Is there a way to parse it based on Content-Type defined in the schema?

Checklist

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingopenapi-fetchRelevant to the openapi-fetch library

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions