3

I have a JavaScript that makes a Fetch post call to the backend of the site. If the post-call goes well, the Fetch is able to handle the response. If something goes wrong in the post-call, the Fetch is not able to handle the error.

This are my codes:

async function startFetch(url, data_post){ 
  return fetch(url, {
    method: 'POST', // or 'PUT'
    body: JSON.stringify(data_post), // data can be `string` or {object}!
    headers:{  
      'Content-Type': 'application/json'
    }
  })
  .then(response => response.json());
}

async function makeFetch(arrRows){
  let url = 'somebackendpost';

  for(const item of ArrRows){
    let data_post = {};
    data.name = item;

    await startFetch(url, data_post)
    .then(data => {
      //when the fetch is okay, this part is executed
      console.log(data);
      //do other things like output to html
      $('#result').append('<p>' + data.result + '</p>');
    })
    .catch(error ={
      //a timeout 504 error occured, but this part seemed not to execute
      console.log('error is', error);
      //the code below is wrong (but has since been removed then)
      //Is this the reason why the catch error part did not work?
      //Since the code below has been removed, can I expect the catch error to now work?
      $('#result').append('<p>' + data.result + '</p>');
    });

  }
}

function startProcess(){
  //called by button click
  let arrRows = ["Row1", "Row2", "Row3"];
  makeFetch(arrRows);
}

At the time, the code was executed, there was a server issue. The browser console displayed a Gateway timeout error 504. Here is the console logs:

Fetch failed loading: POST "mysite/somebackendpost"
POST mysite/somebackendpost 504 (GATEWAY TIMEOUT)
error is SyntaxError: Unexpected end of JSON input
 at fetch.then.response
Uncaught (in promise) ReferenceError: X is not defined
  at startFetch.then.catch.error

1 Answer 1

3

Try updating your startFetch method to first check that the fetch response is "ok" before attempting to parse the response as json. This will catch most error scenarios (that are currently going undetected), before you attempt to parse json.

So, an update as follows should allow you to respond to errors correctly:

async function startFetch(url, data_post){ 
  return fetch(url, {
    method: 'POST', // or 'PUT'
    body: JSON.stringify(data_post), // data can be `string` or {object}!
    headers:{  
      'Content-Type': 'application/json'
    }
  })
  .then(response => {

      // Check that the response is valid and reject an error
      // response to prevent subsequent attempt to parse json
      if(!response.ok) {
         return Promise.reject('Response not ok with status ' + response.status);
      }

      return response;
  })
  .then(response => response.json());
}

Hope this helps!

Sign up to request clarification or add additional context in comments.

2 Comments

@JaimeDolorjr. you're welcome - let me know if you need any more help :)
I make a slight improvement. The reject now reads return Promise.reject('Response not ok with status ' + response.status); This worked like a charm :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.