Andre Calenta
Andre Calenta

Reputation: 87

Detect error in javascript (in code) and act accordingly

I have some var data which might have a data[0].substring(1)[1] or it might won't (regarding the .substring())

I can't change the data I receive, neither does it come in a specified format. Please don't ask about it, the idea of this question is precisely to answer in this scenario.

I tried to do this

if(data[0].substring(1)[1]){

}

but it fails anyway with Cannot read property 'substring' of undefined so now I'm in doubt on how I should do this.

Is this possible? Is there a workaround?

Upvotes: 0

Views: 61

Answers (2)

Shooky
Shooky

Reputation: 1299

You should check whether data[0] exists before trying to access it:

if(data[0] && data[0].substring(..)) {
  ...
}

Upvotes: 1

Charly
Charly

Reputation: 160

Use try/catch/finally:

var txt;
try{
    txt=data[0].substring(1)[1];
}
catch(e){
    console.log(e);
    console.log("The variable does not contain this data."); // at your own choice
}
finally{
    if(txt!=undefined){
    // do stuff with txt
    }
}

Upvotes: 0

Related Questions