Skip to content Skip to sidebar Skip to footer

How Control Javascript Error When Json Is Empty

I am parsing a JSON file in javascript. Every 5 minutes the JSON is autoimatically updated with new data, during the time it is being updated the JSON is blank (for a about 2 secon

Solution 1:

This should do the trick. then() takes a second callback function as argument that receives the error object.

fetch("http://location/file/data.json")
          .then(res => res.json(), err =>console.log(err)) 
          .then(data => {
            //do something
          }, err =>console.log(err))

EDIT: As per comment, this way is preferred. Can read more about using promises in this link

fetch("http://location/file/data.json")
          .then(res => res.json()) 
          .then(data => {
            //do something
          })
          .catch(err =>console.log(err)

Solution 2:

You can add .catch into your processing:

fetch("http://location/file/data.json")
     .then(res => res.json()) 
     .then(data => {
         // do something
     })
     .catch(err =>console.log(err.message))

EDIT: err.message instead of JSON.stringify(err).

Post a Comment for "How Control Javascript Error When Json Is Empty"