Search code examples
javascriptformsgoogle-apps

How to retry DriveApp.getFileById, if error occurs, until successful


I have created a function that is saved within a google form response spreadsheet. As a form is submitted, it takes each data point and populates them into a google word document saved on drive, it then creates a PDF of the document and emails it to the individual that submitted the form.

About 5% of the time, an error occurs during the phase of code which the function calls DriveApp.getFileById(docTemplate). The error is always the same "We're sorry, a server error occurred. Please wait a bit and try again. (line 186, file "Code")"

I have come to think this is a network issue, and as a user has a bad connection to the internet it can not open the docTemplate file therefore it errors.

I would like to create some sort of a loop that tries the function a number of times until it successfully completes the function. When the error happens it becomes a huge pain administratively to ensure the user gets their document in a timely manor!

Code I have is rather long. It begins by setting variable, then using a few if's to further define some variables, then goes directly to:

var copyId = DriveApp.getFileById(docTemplate) //line 186
.makeCopy(docName+' for '+ name)               //line 187
.getId();                                      //line 188

After this it then saves and closes the doc, converts the temp doc to a PDF, then sends the email with attachments.

Again, the program runs perfect 95% of the time with no issues. It just seems that possibly internet connection could be the issue.


Solution

  • Maybe you can wrap this part in a try-catch block and then call it in a loop until the copy is made. And inside the main function, you can call copyTemplate(), until the return value is not null.

    function copyTemplate(docTemplate, docName, name) {
     try {
       var copyId = DriveApp.getFileById(docTemplate) //line 186
                      .makeCopy(docName+' for '+ name)               //line 187
                      .getId();  
       return copyId; 
     } catch (e) {return null;}
    }