Search code examples
javascriptlanguage-features

How do you exit the caller function in JavaScript?


It is possible to return from/exit the caller function i JavaScript?

We are adding testing methods to our framework and we want to exit if we have an error on an Assertion.

Given the following simple example code i would like to exchange EXIT_TEST_THAT_CALLED_ME for something that will exit ( equivalent to doing return in the test ) the method Test123.

Assert = function ( expectedTrue, comment ) {
    if( ! expectedTrue ) {
      Log.Error( comment );
      EXIT_TEST_THAT_CALLED_ME;    
    }
}

Test123 ( ... ) {

  var inputField = getInputField(".input");
  Assert( (inputField !== null ), "Checking that we found an input field");

  inputField.doSomething();
  // This row will cause run time error if inputField is null  

}

What I have tried
return - Of course not works since it only returns from the Assert Method
arguments.callee.caller.return - Does nothing
arguments.callee.caller.return() - Has no method 'return'

Note
Changing to a Test Framework which already has this and where everything is nice is not an option. :(


Solution

  • One option would be to use try\catch\throw

    Assert = function ( expectedTrue, comment ) {
        if( ! expectedTrue ) {
          Log.Error( comment );
          throw "OOPS";
        }
    }
    
    try{
      // function that users Assert
      Test123 ( ... )
    }
    
    catch(err){       
        alert(err);
        if (err=="OOPS"){
        //special handling for a certain exception
        }
    }
    

    Using this flow, the moment the exception is thrown, it will propagate upwards until it reaches the catch block for you to handle the exception.

    Also, the exception isn't limited to be a string. It can be an integer, Boolean or an object.