skip to Main Content

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?

2

Answers


  1. 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

    Login or Signup to reply.
  2. In such cases, it might be beneficial to handle the response status within the catch block by examining the error object directly, as the response object might not be accessible. Here’s an alternative approach:

    } catch (error) {
      if (error instanceof TypeError && error.message === "Failed to fetch") {
        console.log("Network error. Check your internet connection or the server availability.");
      } else if (error instanceof Error && error.message.includes("403")) {
        console.log("HTTP error! Status: 403 Forbidden");
      } else {
        console.log("Error", error);
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search