We start by getting the template file that we want to make a copy of but wrap this within a try/catch. As part of getting the file we include an additional variable (gotTemplateFile) set to either true or false depending upon success, which we can then use to determine if the script should proceed with the next step. We also make use of the logEvent Function to output any errors messages:
try {
// get template file
var templateFile = DriveApp.getFileById(templateFileId);
var gotTemplateFile = true;
}
catch(e) {
logEvent('Problem with template file, error: ' + e);
var gotTemplateFile = false;
}
If we were unable to 'getFileById' for instance then the variable (gotTemplateFile) would be set to false and the following 'if' statement would not evaluate as true:
if (gotTemplateFile) {If the above is successful then the script proceeds to 'getFolderById' for the parent and we have a new variable we set the value of. If the statement evaluates as false then we can return the value of gotTemplateFile to the parent Function which can handle how it should proceed.
try {
// get parent Google Drive folder
var parentFolder = DriveApp.getFolderById(parentFolderId);
var gotParentFolder = true;
}
catch(e) {
logEvent('Problem with parent Google Drive folder, error: ' + e);
var gotParentFolder = false;
}
}
else {
return gotTemplateFile;
}
The script proceeds in the same manner for getting the parent Google Drive folder and either returns an array of name:value pairs (detailed more in this blog post) which we ultimately want for a successful Function or the Boolean value of our variable.
Create a copy of a file using try/catch
No comments:
Post a Comment