Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stop javascript executing when catch error

Tags:

javascript

I need a function that stop execute javascript when catch error. For example as follow:

function AA()
{
  try{
    executeScript();
  }catch(e){
    //stop execute javascript
  }
}

function executeScript()
{
   throw 'error';
}
function BB()
{
  //some script
}
AA();
BB(); //don't execute when error happening

Has anybody know how to do it? Thanks for help.

like image 464
正傑 楊 Avatar asked Dec 27 '22 22:12

正傑 楊


2 Answers

I think if you use a return it should be possible :)

function AA()
{
  try{
  }catch(e){
    //stop execute javascript
    return;
  }
  BB(); //don't execute when error happening
}

function BB()
{
  //some script
}

return like that will just return undefined. You can return something more specific like a string or anything else to be able to have a convenient behaviour when you get this early return.

like image 104
Jeremy D Avatar answered Jan 14 '23 03:01

Jeremy D


There are two ways,

  1. Add return statement

     function AA()
     {
       try{
       }catch(e){
         return;
       }
       BB();  
     }
    
     function BB(){   
     }
    
  2. If you want to return from in code before catch calls you can add throw

    function AA() {           
        try{
           javascript_abort();
         }catch(e){
            return;
         }
         BB();  
        }
    
    
     function BB(){   
             }
    
         function javascript_abort(){
            throw new Error('This is not an error. This is just to abort javascript');
         }
    
like image 38
Umesh Aawte Avatar answered Jan 14 '23 03:01

Umesh Aawte