Javascript multiple “try”s

后端 未结 3 592
不思量自难忘°
不思量自难忘° 2021-01-14 04:53

We all know the basic escaping mechanism in JS:

try {
    ...
}
catch(err) {
    ..
}

I have a JSON data in which I want to check if a lead

3条回答
  •  迷失自我
    2021-01-14 04:59

    Instead of do this in using one try-catch block only. As we know when we will get type error in javascript when access something that does not exist.

    See the below code snippet.

    function getName(isFullName='true'){
    
      try{
         if(isFullName)
           name = lead['Details']['Name']['Full'];       
         else
           name = lead['Details']['Name']['First'] + " " + lead['Details']['Name']['Last'];       
         }
       catch(e){
         if (e instanceof TypeError && isFullName) 
             getName(false);
         name = 'No name';   
        }
    } 
    

    In case name is full name is coming undefined then, we need to add an extra if block to check for the undefined case.

提交回复
热议问题