Home > Software design >  Try catch and continue with a script to get folder paths from a Google URL ID
Try catch and continue with a script to get folder paths from a Google URL ID

Time:12-01

I have a script that is executing as desired. I have Google URL ID's in column A and I am able to run the script below to get the folder path. I included a try catch statement as well. When I get to a URL/ID I don't have access to, I want the app script to log it but continue. I haven't found the appropriate code to make that last piece happen. The script runs until the error is met.

function getFolderPathFromFileId() {
  try{
    const ss = SpreadsheetApp.getActiveSpreadsheet();

    //Change sheetname:
    const sheet = ss.getSheetByName('Sheet1');
    //Startrow = 2 | Column = 1 | Use method to get the last row of the file. --> So: A2:A(x)
    const ids = sheet.getRange(2, 1, sheet.getLastRow() - 1)
      .getValues()
      .flat()
      .filter(id => id != "");

    

    const allPaths = []; 

    ids.forEach(id => {
      const filePath = [];
      const file = DriveApp.getFileById(id);
      let parent = file.getParents();
      if (!parent) {return;
      } 
         else{
        while (parent.hasNext()){
          const folder = parent.next()
          const folderName = folder.getName();
          filePath.unshift(folderName);
          parent = folder.getParents();
        };

        const chainedFolderNames = filePath.join('/');
        console.log(`ID: ${id} --> ${chainedFolderNames}`)
        allPaths.push([chainedFolderNames])
      } sheet.getRange(2,2, allPaths.length, 1).setValues(allPaths);


    });  

    //Startrow = 2 | Column = 2
    //sheet.getRange(2,2, allPaths.length, 1).setValues(allPaths);

  } catch (err) {
    // Handle exception for IDs that you don't have access or it is invalid
    Logger.log('Failed with error %s', err.message);
    
  }
}

I built the script from a few links, but primarily sourced this one - https://www.reddit.com/r/GoogleAppsScript/comments/ryoi40/get_a_folder_path_from_a_file_id/

I admit I am not comfortable with scripting. I reviewed this site as well but I didn't understand how to use the information in the post.

Try...catch not working as expected in Google Apps Script

CodePudding user response:

function getFilePathFromIdOrUrl() {
  const resp=SpreadsheetApp.getUi().prompt("Path from Id or Url", "Enter Id or Url", SpreadsheetApp.getUi().ButtonSet.OK_CANCEL)
  if(resp.getSelectedButton()==SpreadsheetApp.getUi().Button.OK) {
    const id=resp.getResponseText();
    if(id) {
      var s=id.slice(0,6);
      if(s!='https:') {
        var file=DriveApp.getFileById(id);
      }else{
        var file=DriveApp.getFileById(id.slice(id.indexOf('/d/') 3,id.indexOf('/edit')));
      }
      var pA=[];
      pA.push(file.getName());
      var folder=file.getParents();
      while(folder.hasNext()) {
        var f=folder.next();
        pA.push(f.getName());
        folder=f.getParents()
      }
        var path=pA.reverse().join(' / ');
      SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(path), 'Path for: '   file.getName());
      //return path;
    }else{
      SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput('Error: Invalid Input: No id.'), "getFilePathFromId Error")
    }
  }
}
  • Related