MOHIT SHARMA
MOHIT SHARMA

Reputation: 103

How to check whether response JSON of an API is empty or has an error?

I am new to reactjs and I am stuck in one problem. I am calling an Update API which is of PUT type. I use the fetch function to call the API in reactjs and I check the response of the API. If Response is 200 OK, then I return the response.json() and then check whether the json object has error in it or not. If it has error, then I print the error else I update it.

But when there is no Error present in the response, then I get a syntax-error in return response.json() statement and If there is actually a Error present in the response then there is no syntax-error shown. So is there a method to check whether the response is empty or not so that accordingly I can return response.json().

I have tried by putting a condition as if(response.json() != '') but it shows error in response.json() statement.

fetch( API + name , {
      method: 'PUT',
      headers: {
         'Accept' : 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + localStorage.getItem('access_token')
      },
      body: JSON.stringify({
        name: name,
        description: updateDesc
      }),
    }).then(function(response) {
      if(response.status == '200'){
        flag=true;
        return response.json();
      }
      else {
        flag=false
      }
    })
    .then(json => {
    if(flag)
    {
        if(json.Error != "")
        {
          that.createNotification('error','update');
        }
        else {
          this.createNotification('success','update');
        }
    }
});

Unhandled Rejection (SyntaxError): Unexpected end of JSON input

Upvotes: 3

Views: 8818

Answers (1)

Leo
Leo

Reputation: 1800

There are multiple issues with this imo:

  1. The callback should be refactored to avoid the use of the flag variable. The code in the function supplied to handlers like then, catch and finally of promises is executed asynchronously. Therefore you cannot be sure / (should not assume) when this value will be assigned and in which state your context is at that time.

  2. .then(json => { if there is an error this will actually use the promise returned by fetch aka response and not the promise returned by response.json() (Currently return response.json() is only executed in the success case)

Note that this happens (currently works in the error case) because you can chain promises. You can find more info and examples about this here

I would refactor the handling of the fetch promise like this:

const fetchPromise = fetch(url, { method: 'PUT', ...yourParams });

fetchPromise.then(response => {
  if (response.ok()){
    //Your request was successful
    const jsonPromise = response.json();
    jsonPromise.then(data => {
      console.log("Successful request, parsed json body", data);
    }).catch(error => {
      //error handling for json parsing errors (empty body etc.)
      console.log("Successful request, Could not parse body as json", error);
    })
  } else {
    //Your request was not successful
    /*
     You can check the body of the response here anyways. Maybe your api does return a json error?
    */
  }
}).catch(error => {
  //error handling for fetch errors
}))

Upvotes: 4

Related Questions