How to get fetch status code when it fails with "TypeError: Failed to fetch"?

122 Views Asked by At

I have the following code:


    let response = null;
    try {
      response = await fetch(url, { method,
        headers: {
          Authorization: `Bearer ${accessToken}`,
        }
      });
      console.log("Status", response?.status);
    } catch (e) {
      console.log("Error", e);
      console.log("Response", response);
    }

My request fails with status code 403, but I cannot get this 403 from nowhere. The code above doesn't get to the line console.log("Status", response?.status);, instead it goes into catch section, where response is undefined and e is error with message "TypeError: Failed to fetch" and stacktrace, but without any further details about the response (actually, I looked for response status code).

screenshot of failed fetch with 403 status code

Does anybody have idea how do I get that status code (403 in my example) when fetch fails into catch section?

1

There are 1 best solutions below

1
twalow On

Try using response.ok https://developer.mozilla.org/en-US/docs/Web/API/Response/ok

Using your example:

if (response.ok) {
    console.log("Status", response.status);
} else {
    console.log("Response is not OK, status:", response.status);
}

By using 'response.ok' you're checking for error codes 200-299