skip to Main Content

I’m using a twitter api to get information about tweets. My code is using this information. Sometimes does it happen, that the api delivers an ‘undefinded’ and my code stops.

My idea was to check the parameters and only work with those who are okay:

if ( typeof data.id_str.user.name === 'undefined' || data.id_str.user.name === null ){ 
  next(); 
} else{
    return data.id_str.user.name;
}

But my check doesn’t matter. If I execute the code the TypeError still happens sometimes: “Cannot read property ‘name’ of undefined”. Do you have an idea what I could do to handle this error and check the next tweet?

data is not defined. But I don’t know, when data will not be defined. I need a way to skip the data and use the next defined data.

I have implemented your suggests. The error appears now for the else part of the if condition. Why? And how could it work?

if ( typeof data && data.id_str && data.id_str.user && data.id_str.user.name === 'undefined' || data && data.id_str && data.id_str.user && data.id_str.user.name === null ){
              console.log('data.id_str.user.name is undefined. --> Why?');              
            } else {
              console.log('on User  : '+data.id_str.user.name);
              }

2

Answers


  1. You can use ‘guarding’. Do like: typeof data && data.id_str && data.id_str.user && data.id_str.user.name === "undefined"
    Simple sollution but helps to not lock code.

    Edit: here I have found you more described example of such guarding against undefined: Guarding against undefined parameters

    Login or Signup to reply.
  2. In this case, any of the chain of data may be undefined, e.g. data.id_str may be undefined or data.id_str.user may be undefined. The latter case will cause:

    Cannot read property ‘name’ of undefined

    There are several ways to handle this such as checking each individual piece in the chain data && data.id_str && data.id_str.user or wrapping the retrieval in try/catch.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search