Google Apps Script: “We’re sorry, a server error occurred. Please wait a bit and try again.” occurs sporadically for this script

This script typically runs smoothly, but out of every 100 form submissions, I get a failure at line 59. I can’t find any commonality between the submissions that receive this error. Currently I just monitor the script failures and run the failed submissions through a manual version of this script to send the filled documents, but I would like to find a way to avoid the error entirely.

// Global variables 
var docTemplate = "doc id code";  // *** replace with your template ID ***
var docName = "Application Form";

function onFormSubmit(e) { // add an onsubmit trigger
  
// Values come from the spreadsheet form  
   var StudentID = e.values[1]
   var First = e.values[2]    
   var Middle = e.values[3]    
   var Last = e.values[4] 
   var DOB = e.values[5]  
   var Gender = e.values[6]
   var Social = e.values[7]
   var Email = e.values[8]    
   var Street = e.values[9]    
   var City = e.values[10]
   var State = e.values[11]
   var Zip = e.values[12]    
   var Cnty = e.values[13]    
   var HomePhone = e.values[14]    
   var Cell = e.values[15] 
   var Ethnicity = e.values[16] 
   var Race = e.values[17] 
   var CEG = e.values[18]
   var CES = e.values[19]
   var edfather = e.values[20]
   var edmother = e.values[21]
   var ecname = e.values[22]    
   var ecphone = e.values[23]    
   var ecrelationship = e.values[24] 
   var school = e.values[25] 
   var grade2 = e.values[26]    
   var graddate = e.values[27]    
   var counseloremail = e.values[28] 
   var Semester = e.values[29] 
   var Year = e.values[30]
   var priorclasses = e.values[31]  
   var priorprogram = e.values[32]    
   var ProgramChange = e.values[33] 
   var transferpathways = e.values[34] 
   var CTEpathways = e.values[35]
   var regfortransfer = e.values[36]
   var Coursesrequested1 = e.values[37]
   var Coursesrequested2 = e.values[38]
   var Coursesrequested3 = e.values[39]
   var Coursesrequested4 = e.values[40]
         
 //Copy response to school's sheet
var responses = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
  var dest =  SpreadsheetApp.getActiveSpreadsheet().getSheetByName(school);
  var lastrow = responses.getLastRow();
  var col = responses.getLastColumn();
  var row = responses.getRange(lastrow, 1, 1, col).getValues();
    dest.appendRow(row[0]);
  //copyValuesOnly(copyFromRange, copyToRangeStart);
       
// Get document template, copy it as a new temp doc, and save the Doc’s id
   var copyId = DriveApp.getFileById(docTemplate)
                .makeCopy(docName +' for '+ StudentID + ' (' + Semester + Year + ')' )
                .getId();
  
// Open the temporary document
   var copyDoc = DocumentApp.openById(copyId);
  
// Get the document’s body section
   var copyBody = copyDoc.getActiveSection();
  
// Replace place holder keys,  
  copyBody.replaceText('Key_StudentID', StudentID);
  copyBody.replaceText('Key_First', First);
  copyBody.replaceText('Key_Middle', Middle);
  copyBody.replaceText('Key_Last', Last);
  copyBody.replaceText('Key_DOB', DOB);
  copyBody.replaceText('Key_Gender', Gender);  
  copyBody.replaceText('Key_Social', Social);
  copyBody.replaceText('Key_Email', Email);
  copyBody.replaceText('Key_Street', Street);
  copyBody.replaceText('Key_City', City);
  copyBody.replaceText('Key_State', State);  
  copyBody.replaceText('Key_Zip', Zip);
  copyBody.replaceText('Key_HomePhone', HomePhone);
  copyBody.replaceText('Key_Cell', Cell);
  copyBody.replaceText('Key_Ethnicity', Ethnicity);  
  copyBody.replaceText('Key_Race', Race);
  copyBody.replaceText('Key_CEG', CEG);
  copyBody.replaceText('Key_CES', CES);
  copyBody.replaceText('Key_edfather', edfather);
  copyBody.replaceText('Key_edmother', edmother);  
  copyBody.replaceText('Key_ecname', ecname);
  copyBody.replaceText('Key_ecphone', ecphone);
  copyBody.replaceText('Key_ecrelationship', ecrelationship);
  copyBody.replaceText('Key_school', school);  
  copyBody.replaceText('Key_grade2', grade2);
  copyBody.replaceText('Key_graddate', graddate);
  copyBody.replaceText('Key_counseloremail', counseloremail);
  copyBody.replaceText('Key_Semester', Semester);
  copyBody.replaceText('Key_Year', Year);  
  copyBody.replaceText('Key_priorclasses', priorclasses);
  copyBody.replaceText('Key_priorprogram', priorprogram);
  copyBody.replaceText('Key_ProgramChange', ProgramChange);
  copyBody.replaceText('Key_transferpathways', transferpathways);  
  copyBody.replaceText('Key_CTEpathways', CTEpathways);
  copyBody.replaceText('Key_Coursesrequested_1', Coursesrequested1);
  copyBody.replaceText('Key_Coursesrequested_2', Coursesrequested2);
  copyBody.replaceText('Key_Coursesrequested_3', Coursesrequested3);
  copyBody.replaceText('Key_Coursesrequested_4', Coursesrequested4);
  copyBody.replaceText('Key_Cnty', Cnty);
                       
   var todaysDate = Utilities.formatDate(new Date(), "GMT", "MM/dd/yyyy"); 
   copyBody.replaceText('keyTodaysDate', todaysDate);
  
// Save and close the temporary document
   copyDoc.saveAndClose();
  
// Convert temporary document to PDF by using the getAs blob conversion
   var pdf = DriveApp.getFileById(copyId).getAs("application/pdf"); 
  
// Attach PDF and send the email to school faculty
   var subject = docName +' for '+ First + ' ' + Last + ' (' + Semester + Year + ')' ;
   var body    = "email text"
  MailApp.sendEmail('addresses for administrators', subject, body, {htmlBody: body, attachments: pdf});
  MailApp.sendEmail(counseloremail, subject, body, {htmlBody: body, attachments: pdf});
  
// Attach PDF and send the email to student
   var subject = docName +' for '+ First + ' ' + Last + ' (' + Semester + Year + ')' ;
   var body    = "email text"
   MailApp.sendEmail(Email, subject, body, {htmlBody: body, attachments: pdf});
  
  // Delete temp file -- Disabled
   //DriveApp.getFileById(copyId).setTrashed(true);
   
   

}

Answer

This looks to be a duplicate of File.makeCopy error, but I can’t flag it since the other question doesn’t have an accepted/upvoted answer.

Sometimes .makeCopy returns this error unexpectedly. You should move the line that fails into a loop (say repeat 3 times) with a try-catch breaking the loop on success and sleeping on failure.

I don’t really write javascript, but something like this:

function sleep(milliseconds) {
  return new Promise(resolve => setTimeout(resolve, milliseconds));
}

async function onFormSubmit(e) {

    /* Your code here */
  
    var file = DriveApp.getFileById(docTemplate);
    var copy;    
  
    var i = 0;
    while(i < 3) {
        try {
            copy = file.makeCopy(docName +' for '+ StudentID + ' (' + Semester + Year + ')' );
            break;
        }
        catch(e) {
            await sleep(5000);
            i++;
        }     
    }
  
    if (copy == undefined) {
        throw "Copy failed 3 times in a row";
    }

    var copyId = copy.getId();

    /* More of your code here */
  
}

Other SO that helped me get there: