JackU
JackU

Reputation: 1476

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 seconds).

I get this error

Uncaught (in promise) SyntaxError: Unexpected end of JSON input at fetch.then.res

This is the code in javascript for parsing the JSON:

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

How do I control this so that it doesn't flag this error? I still want an a customer error to appear using console.log(Error()).

Any help is appreciated.

Upvotes: 1

Views: 269

Answers (2)

ttulka
ttulka

Reputation: 10882

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

Upvotes: 2

Thanthu
Thanthu

Reputation: 5058

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)

Upvotes: 2

Related Questions