JSON call undefined and breaks

时间:2018-03-25 19:11:00

标签: json exception-handling undefined call

I am trying to do a JSON call to get the number of comments of my posts, and it works as long as the post has comments enabled. However if a post hasn't comments enabled, the JSON call returns 'undefined' and my code breaks. I would like to handle this exceptions and in case the value is 'undefined', store a 0 value and continue my script with no breaks.

This is my code:

if(json.feed.entry[i].thr$total.$t == "undefined"){
        comments[i] = 0;
    }else{
        comments[i] = json.feed.entry[i].thr$total.$t;
    }

But my code is not working properly and it breaks. I can see this message in my browser console:

TypeError: json.feed.entry[i].thr$total is undefined[Learn More]

Thank you.

1 个答案:

答案 0 :(得分:0)

Finally I found out the way, using try/catch:

try {
    comments[i] = JSON.parse(json.feed.entry[i].thr$total.$t)
} catch (e) {
comments[i] = 0;  
}

BR.