Kevin
Kevin

Reputation: 3

Is there a way to stop an automatically running script in the middle of execution?

To start I'm a carpenter not a developer.

I'm using google forms to automate my estimating for jobs. I have a script that formats the answers to pdf so they can be sent to my main customer for approval. The masterFunction() is triggered by the form submit. The script I've written is maybe not the correct way to do this but its as follows;

function masterFunction() {
    aFunction();
    bFunction();
    cFunction();
    ...
};

function a(){
   ...
};

function b(){
   ... 
};       
...

If the script encounters an error in any of the child functions I would like to save the work up to then in a different file and clean up so that the next form response can run. Afterwards I can go back and correct the problems and run the rest of the script.

I already have places in the code to catch these errors, such as a blank field, or a null value, or something i've not entered correctly on the form (but not script errors, I'm not concerned about these), that sends me an email alert to these problems but somebody else may send these pdfs to the customer and not see the problem.

Is there a way to to do this that stops the masterFunction(). Most everything I've found will stop the child function, such as break or try, but that only sends it back to the master function which will continue and send it to the next function and run to the end.

Upvotes: 0

Views: 145

Answers (1)

Cameron Roberts
Cameron Roberts

Reputation: 7367

One option is to use the "return" statement, which allows you to return a value from your functions. When you call return, the function ends immediately and optionally passes a value back to the parent, which you can check.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return

Modify your child functions to use the 'return' statement and return a 'true' value on success, and 'false' on failure, then check the results of each:

in function:

return false;

in master:

var a_result = aFunction();
if(!a_result){
    /*... optionally do "failed" tasks here ..*/
    return  //exit master function
}

Another option is to "throw" an exception, which you can then "catch" in your master function. Raising an exception might work better if you don't care which of your child functions failed.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw

In child:

throw "missing name!"

In master:

   function masterFunction(){
    try{
       aFunction();
       bFunction();
       ...
    }catch(e){
        logger.log('Caught error '+e);
    }
   }

Upvotes: 1

Related Questions