Tuesday 28 April 2020

Create a copy of a file using try/catch

The following Google Apps Script code is designed to create a copy of a template file and return its Url & ID. It is designed as a Function that would sit within your existing code (hence there are input parameters) and it makes extensive use of 'try/catch' in order to capture any errors that could occur. It also makes use of our log actions code detailed in this blog post so we can output the error somewhere.

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) {
    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;
  }
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.

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