I've been having an issue with a Google Apps Script I'm running that kept throwing the following error when ever I triggered the code onChange. No such errors were returned when I manually ran the code.
Exception: Service Documents failed while accessing document with id XXXX
The error was happening on the same line of code each time and I've subsequently found that this is a relatively common error and is perhaps happening because my script is quite lengthy and perhaps not as efficient as it should be (I'm very much an Apps Script and JS novice). Interestingly I have a very similar script (with perhaps 20% less variables) running in another file that executes as expected every time.
I had no naming or scoping issues with the variable that was being used to call the document but I thought that perhaps wrapping the troublesome part of the script into a self-invoking function within the larger function would minimise hoisting and improve the efficiency of the script - at least enough to let it run consistently without errors. My understanding of JS is that when a script initiates variable declarations are hoisted within their scope and therefore by creating a self-invoking function I could reduce the hoisting within the main function which contains in excess of 100 variables and therefore reduce the initial demand.
So far the script does appear to be running more quickly and avoiding the error that I'd previously being seeing - the last run was just over 63 seconds whereas the previous successful manual run without the self-invoking function was just under 103 seconds.
I do believe this can be an intermittent error and I'm trying to find a robust, longer term fix without having to rewrite all of my code.
I have detailed the self-invoking code below with any IDs redacted. The part that was causing the error within the script was "var docFinal = DocumentApp.openById(docFinalId);
Do you think this could be a genuine fix or has the code started to work coincidently because of the intermittent nature of this error?
var docTempId = "XXXX";//Template File Id
var docFinalId = "XXXX"; //Final File Id
var sheetId = "XXXX";
(function () { // self-invoked within larger function to minimise hoisting
var docTemp = DocumentApp.openById(docTempId);
var docFinal = DocumentApp.openById(docFinalId);
docFinal.getBody().clear();
var templateParagraphs = docTemp.getBody().getParagraphs();
createMailMerge(Company,Branch,PropertyID,PropertyAddress,ApplicantName,Dateofbirth1,EmailAddress,PhoneNumber,Nationality,PassportNumber,NationalInsuranceNumber,Currentresidentialstatus,LeaseRequested,RentOfferedPCM,TotalNumberofAdultOccupants,Proposedleasecommencementdate1,TotalRentPayers,RentPayer2Name,RentPayer2Phone,RentPayer2Email,RentPayer3Name,RentPayer3Phone,RentPayer3Email,Relationshipwithadultoccupants,Numberofchildren,Ageofchildchildren,Currenteconomicstatus,Applicantoccupation,Applicantemployedorselfemployed,ApplicantDeclaredIncome,SelfEmployedDocuments,EmploymentPartorFullTime,EmploymentContractorPermanent,MainEmploymentCompany,Mainemploymentaddress,Mainemploymentstartdate1,Mainemploymemtpensionpayrollnumber,MainEmploymentManager,ManagerEmail,ManagerPhoneNumber,ApplicantPaymentType,ApplicantHourlyRate,Applicantprimaryaveragehourspermonth,Applicantsalary,ReceivesHousingBenefit,HousingBenefitAmount,Anyadditionalincome,Typeofadditonalincome,Secondemploymentcompany,Rolewithin2ndCompany,ndEmployeraddress,ndEmploymentstartdate1,ndEmployerpensionpayrollnumber,ndEmploymentContact,ndEmploymentEmail,ndEmploymentphonenumber,Additionalincomeamount,Additionalincomedetails,TotalDeclaredGrossIncome,Applicansavingsdeclared,MostRecentAddress,DateStartedlivingincurrentaddress1,Liveanywhereelseinlast3years,Applicant2ndresidingaddress,Applicant2ndaddressmoveindate1,Applicant2ndaddressmoveoutdate1,Applicantadditionaladdressdeclared,Applicantadditionaladdressdetails,Applicantadditonaladdressmoveindate1,Applicantadditionaladdressmoveoutdate1,Applicantpreviouslandlordreference,Landlordreferenceaddress,referencefromlandlordoragent,LandlordAgentName,lengthoftimeatproperty,LandlordAgentphonenumber,LandlordAgentemailaddress,Previouslandlordreferencepreventionreason,Anypets,Petdetails,Applicantsmoke,Applicantsmokeinside,Applicantadversecredit,Adversecreditdetails,Applicantprovidecurrentaccount,Applicantcurrentaccountname,Applicantcurrentaccountbank,Applicantcurrentaccountnumber,Applicantcurrentaccountsortcode,UKbasedguarantor,GuarantorName,GuarantorEmail,GuarantorPhoneNo,Noguarantorreason,NextofKinName,NextofKinrelationship,NextofKinEmail,NoNextofKinPhoneNo,Applicantadditionalinfo,Applicantdocuments,Applicantaccurateinformationdeclaration,Applicantaccepttermsandconditions,submittedatt,Token,maidenname,ApplicantReferencingChoice,Applicantcanprovide,Applicantdocumentlink,ApplicantacceptsHomelet,ApplicantallowsHomelettocontactreferences,ApplicanthappyforHomelet,templateParagraphs,docFinal);
docFinal.saveAndClose();
createPDF(); // calls the next function
}) ();
The script has just failed again. After working on a number of occasions which hadn't been happening, it has now failed and return the same error as before. I can therefore only assume that creating a self-invoking function within the main function has made no material difference to the efficiency of the script.
The error you are receiving does not seem to be the expected one.
I think the best solution in this situation is to file a bug on Google's Issue Tracker by using the template here.
This is related to this thread. I don't know what the problem is since I'm just new with this coding thing. But I found the error when I clicked the latest code below the URL.
This is the error TypeError: this[e.parameter.run] is not a function (line 2, file "Code").
And, this is the code:
function doGet(e) {
this[e.parameter.run](e.parameter.sheetName || null); //this is line 2
return ContentService.createTextOutput();
}
Honestly, I don't know what that function does since I just copy it on this solution. But as far as I understand, it helps for the script to be accessible to other users. What seems to be the problem here?
Explanation
You function doGet(e) expects a parameter run to which the name of an (existing) function is assigned.
This paramter has to be appended to the WebApp URL
If you call the WebApp without assigning it any paramater (by pressing on latest code) the function will error
Instead, you need to copy the Current web app URL and append to it ?run=NameOfFunction
For example:
https://script.google.com/macros/s/XXXXXXXX/exec?run=myFunction
If your script contains a function called myFunction() - this function will be executed on pasting the full Web App URL including parameter run into the browser address bar.
Recomendation
Modify
return ContentService.createTextOutput();
to return ContentService.createTextOutput("It worked");
This will give you some feedback about the fact that the Web App has been executed correctly.
I want to pass a parameter to my google spreadsheet with a get request. The get parameter name is 'pid', which seems to make Google Sheets crash.
My example script just returns the get parameters to the client:
function doGet(e){
try {
return ContentService
.createTextOutput(JSON.stringify({"result":"your parameters", "parameters": e.parameter}))
.setMimeType(ContentService.MimeType.JSON);
} catch(ee){
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error message": ee}))
.setMimeType(ContentService.MimeType.JSON);
}
}
The following request works:
https://script.google.com/macros/s/<sheet-id-here>/exec?a=1
returns:
{"result":"your parameters","parameters":{"a":"1"}}
But simply changing the get parameter name returns an error:
https://script.google.com/macros/s/<sheet-id-here>/exec?pid=1
returns:
We're sorry, a server error occurred. Please wait a bit and try again.
Any idea what's going on here and how to fix this? Is this a bug? Is there a way to handle this on the server side (can't really change my client code)?
It seems Google has changed reserved parameters. As written in the documentation,
Warning: The following parameter names are reserved by the system and shouldn't be used in URL parameters or POST bodies:
c
sid
Using these parameters may result in an HTTP 405 response with the error message "Sorry, the file you have requested does not exist." If possible, update your script to use different parameter names.
It seems both c and sid parameters are valid now and pid parameter is reserved and throws
Sorry, unable to open the file at this time.
There doesn't seem to be anything that you can do server side.
I am trying to access the HTTP GET variables in a Google Apps Script (Like PHPs $_GET).
I tried several techniques:
Plain java script (window.location), which obviously is not supported
Googles own Service through SitesApp.getActivePage().getUrl(). Gives
me the URL, but without the variable string. On second thought this
might make sense.
e.parameter.[key] This gives me the following error: TypeError: Cannot read property "parameter" from undefined.
I'd really appreciate some pointers or a working example, thanks.
As per the comment from Srik I tried the following:
function doGet(e) {
UserProperties.setProperty("bottleid", e.parameter.id);
return HtmlService.createTemplateFromFile('showbottledata').evaluate();
}
Which gives me the mentioned
TypeError: Cannot read property "parameter" from undefined. (line 2)
error.
First, you need to define your doGet in such a way that it accepts URL parameters
function doGet(e) {
....
}
When you call your URL using URL parameters, say parm1=val1, use
var parm1 = e.parameter.parm1 ;
Playing with the ScriptDB Service, I created a new standalone script with the following function taken from the Documentation. The code throws the "Unexpected exception upon serializing continuation" exception in the var results = db.query({}); line. Am I doing something wrong or it is an issue to the GAS issue tracker?
function showAll() {
var db = ScriptDb.getMyDb();
var results = db.query({});
while (results.hasNext()) {
var result = results.next();
Logger.log(Utilities.jsonStringify(result));
}
}
Dont use the debugger: I had the same problem and read somewhere that the debugger produces this error. While I have not done much checking yet, I agree that it looks like a debugger issue.
Maybe star the issue: http://code.google.com/p/google-apps-script-issues/issues/detail?id=1267
Yes I looked into (googled) those continuation errors and it seems to be an implementation issue/limitation at Google's back end with the Rhino runtime Javascript environment being able to "suspend" when we as users of the IDE set breakpoints and step through code.
I now make sure I write debug lines into a spreadsheet. It can be slower to setup but it works 100% and is good engineering practice and it's usually faster to debug from logs than the slow, line by line stepping through of the code.