Sonny49
Sonny49

Reputation: 555

catch block doesn't get fired when API returns any error

I am making a normal API call, but for some reason I don't see console.log(err) in my catch block when I get 500 error. It always fires console.log(result) in my then block What am I doing wrong?

const startHandler = () => {
    setOpenLoadingModal(true);
    fetch(url, {
      method: 'post',
      body: JSON.stringify(payload),
      headers: headers,
    })
      .then((response) => response.json())
      .then((result) => {
        console.log("🚀 ~ file: index.js ~ line 159 ~ .then ~ result", result)
        const { client_id, token } = result;
        if (!token || !client_id){
          setOpenErrorModal(true);
          return setOpenLoadingModal(false);
        } else{
          return history.push({
            pathname: FORMS_URL.LANDING_PAGE,
          });
      })
      .catch((err) => {
        console.log(err)

        setOpenErrorModal(true);
        setOpenLoadingModal(false);
      });
  };

Upvotes: 3

Views: 892

Answers (1)

Drew Reese
Drew Reese

Reputation: 202608

fetch doesn't reject on 4xx/5xx error status

Using Fetch

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, as soon as the server responds with headers, the Promise will resolve normally (with the ok property of the response set to false if the response isn’t in the range 200–299), and it will only reject on network failure or if anything prevented the request from completing.

Checking that the fetch was successful

You should check the response.ok status.

const startHandler = () => {
  setOpenLoadingModal(true);
  fetch(url, {
    method: 'post',
    body: JSON.stringify(payload),
    headers: headers,
  })
    .then((response) => {
      if (!response.ok) { // <-- check response OK here
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then((result) => {
      console.log("🚀 ~ file: index.js ~ line 159 ~ .then ~ result", result)
      const { client_id, token } = result;
      if (!token || !client_id){
        setOpenErrorModal(true);
        return setOpenLoadingModal(false);
      } else{
        return history.push({
          pathname: FORMS_URL.LANDING_PAGE,
        });
    })
    .catch((err) => {
      console.log(err)

      setOpenErrorModal(true);
      setOpenLoadingModal(false);
    });
};

Upvotes: 2

Related Questions