1

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.

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

1 Comment

While this works, .catch is the canonical and proper way to log the error. In future Node versions (and likely browsers too), not having the .catch will halt execution.
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).

2 Comments

Note that in a browser, the JSON.stringify isn't necessary.
@BenCooper: Good point, it's a habit of mine. err.message would be maybe the best here.

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.