DanielJ
DanielJ

Reputation: 769

Fetch JS retreive eror response

I am calling an API which could potentially return a 40x response with an associated error body which I want to use. I've tried to use a check if the response.ok() and then throw a error with the response.json() which a catch statement will handle however when the catch runs it will only have a Promise {<pending>}.

This was my resulting attempt which returned a promise to setError().

getAPI(path)
      .then((result) => {
        setResult(result);
      })
      .catch((resError) => {
        setError(`${resError}`);
      });

function getAPI(path) {
  return fetch(
    `http://localhost:3000/${path}`,
    {
      method: "GET",
    }
  ).then((res) => {
    if (res.ok) {
      return res.json();
    } else {
      throw res.json();
    }
  });
}

If in my getAPI I simply return res.json() and not check for a success error code then I get the body of the 400 error however I have no way of checking that the response had an error code.

function getAPI(path) {
  return fetch(
    `http://localhost:3000/${path}`,
    {
      method: "GET",
    }
  ).then((res) => {
    res.json();
  });
}

I can see twhen the fetch is resolved res contains the following attributes.

body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 400
statusText: "Bad Request"
type: "cors"
url: "http://localhost:3000/"

Upvotes: 1

Views: 108

Answers (1)

Phil
Phil

Reputation: 164811

The problem is

} else {
  throw res.json();
}

res.json() returns a promise which will not be resolved by throw.

In your else block, try

return res.json().then(err => throw err)

or

return res.json().then(err => Promise.reject(err))

Upvotes: 1

Related Questions