Re: [Apps-Script] Script stops when there is an error. How to continue running it?

1,219 views
Skip to first unread message

Andrew Roberts

unread,
Sep 29, 2021, 3:43:26 AM9/29/21
to google-apps-sc...@googlegroups.com
try/catch should do it. Do you want to share your code.

On Tue, 28 Sept 2021 at 21:23, jmm0979 <jmm...@gmail.com> wrote:
Hi,

I am checking a few folders if I have access to them. However, the script stops right away if there is an error (i.e.g., "Exception: No item with the given ID could be found. Possibly because you have not edited this item or you do not have permission to access it.") and does not continue with the rest of the loop.

I am using the method "try/catch". Is there a way to allow the script to continue running the next row even if there is an error?

Thanks!

--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/CAHL69DWULkbchaN9VBzSp1bKT9FiTbAn1wKQJjOSinFJoxTyqQ%40mail.gmail.com.

jmm0979

unread,
Oct 5, 2021, 6:15:54 PM10/5/21
to google-apps-sc...@googlegroups.com
Hi Andrew,

Here is my code. Basically, I only want to extract folder content (no files, no subfolders).
If there's an error, stop the code and post whatever the error message is then continue on the next row.

While trying to resolve this myself, I saw another error message: "TypeError: Cannot read property "length" from undefined." I think the folder is empty. I am not sure how to call this out.
I am hoping to post "No Folders Found!" if the folder is empty then continue with the next folder check.

folderID ---> get folder list (no files/no subfolders), if yes - get details. else, post "No Folders Found!"
folderID ---> folder access denied, post the error message then continue with the next folderID check

If you could help me figure out what the issue here is, that would be great!

TIA!

===============

// Get Folders Only
function foldersOnly(folderID, dataArr, extractFolderSheet, i) {

var parentFolder = DriveApp.getFolderById(folderID);
var parentFolderName = parentFolder.getName();
var data;

childFoldersOnly(parentFolderName, parentFolder, data, dataArr, extractFolderSheet, i);
}

// Get the details - Folders Only
function childFoldersOnly(parentFolderName, parentFolder, data, dataArr, extractFolderSheet, i) {

var child_Folders = parentFolder.getFolders();

// List folders inside the folder
while (child_Folders.hasNext()) {
var child_Folder = child_Folders.next();

// if the folder is empty, post a message ----> Is this the correct way to check it? I keep getting: "TypeError: Cannot read property "length" from undefined."
if (child_Folder.getFolders().hasNext() == false) {
extractFolderSheet.getRange(i + 2, 3).setValue("No Folders Found!");
}

var child_FolderName = child_Folder.getName();
var data = [parentFolderName + "/" + child_FolderName, child_FolderName,child_Folder.getId(),child_Folder.getUrl()];
dataArr.push(data);
}
}

function get_FoldersOnly() {

try {
var extractFolderSheet = SpreadsheetApp.getActive().getSheetByName('SHEETNAME_HERE');
var extractFolderSheetVals = extractFolderSheet.getRange(2, 1, extractFolderSheet.getLastRow(), extractFolderSheet.getLastColumn()).getValues();

for (var i = 0; i < extractFolderSheetVals.length - 1; i++) {
var folderID = extractFolderSheetVals[i][0];
var folderName = extractFolderSheetVals[i][1];
var status2 = extractFolderSheetVals[i][2];

var statusMsg2 = ["Done", "Exception: No item with the given ID could be found. Possibly because you have not edited this item or you do not have permission to access it.", "TypeError: Cannot read property 'getEmail' of null", "TypeError: Cannot read property 'length' of undefined", "Exception: Specified sleep period exceeds maximum.", "No Folders Found", 'TypeError: Cannot call method "getRange" of undefined.'];

if (folderName == "" && folderID != "" || folderName != "" && folderID == "") {
var ui = SpreadsheetApp.getUi();
ui.alert('Error', 'Please enter the folder name and folder id!', ui.ButtonSet.OK)
return;
}

else if (statusMsg2.indexOf(status2) + 1) {
continue;
}

else {

var dataArr = [];
foldersOnly(folderID, dataArr);

/* Create new sheet to save the output */
var createNewSheet = SpreadsheetApp.create(folderName);
var createNewSheetID = createNewSheet.getId();
var createNewSheetName = createNewSheet.getName();
var sheet1 = createNewSheet.getSheetByName('Sheet1');
sheet1.getRange(2, 1, 1, 4).setValues([["Folder Path", "Folder Name", "Folder ID", "URL"]]).setBackground('#202020').setFontColor('white');
// Save data //
sheet1.getRange(3, 1, dataArr.length, dataArr[0].length).setValues(dataArr);
SpreadsheetApp.flush();

/* Mark as done when complete */
extractFolderSheet.getRange(i + 2, 3).setValue("Done");
}
}
}
catch (e) {
extractFolderSheet.getRange(i + 2, 3).setValue(e); ----> If I get any errors, I'd like the code to post the error message then continue to the next folder (row)
and run the same code above. Is that possible?
}
}

Andrew Roberts

unread,
Oct 7, 2021, 6:50:04 AM10/7/21
to google-apps-sc...@googlegroups.com
Your use of try/catch looks OK, you'll need to step through the code with the debugger and see where the "length" error is coming from. 

Shadeela Humayun

unread,
Jun 18, 2023, 2:27:49 AM6/18/23
to Google Apps Script Community
hi 

here is my code where i am facing a error which is not allowing me to run the script through Trigger. when i RUN manually it works.

function convertExcelSiemenstoGoogleSheet(fileName) {
  var sheetid = '29psNJBbtgnr6hoGL5_UVWL5rCmIzafo-6216TNBW4Jw';
  try {
               
   var fSource = DriveApp.getFolderById('2l_9ZFwEmVl8Mas975bEPPhUTEcei9-Nf'); // reports_folder_id = id of folder where csv reports are saved
  var fileList = fSource.getFilesByName('1. Rematics_Siemens').next();
               
        Logger.log(fileList.length);
               
  sheetid = fileList.getId();
  Logger.log(fileList.getId());
               
   
    var BCON = Lastrow(sheetid);
    Logger.log("Bcon="+BCON);
    fileName = fileName || "1. Rematics_Siemens.xlsx";

    var excelFile = DriveApp.getFilesByName(fileName).next();
    var fileId = excelFile.getId();
    var folderId = Drive.Files.get("2HEU_gKo-Lj4N0n0E1zotbLQeP5BDhvTq", {supportsAllDrives: true}).title;//.parents[0].id;
    var blob = excelFile.getBlob();
   
    var resource = {
      title: excelFile.getName(),
      mimeType: MimeType.GOOGLE_SHEETS,
      parents: [{id: "2l_9ZFwEmVl8Mas975bEPPhUTEcei9-Nf"}],
     
    };
    Logger.log(resource);
 
    let spreadsheet = Drive.Files.insert(resource, blob);
    Drive.Files.remove(sheetid);
 
    var ACON= Lastrow(spreadsheet.id);
    Logger.log("Acon="+ACON);
    var diff= ACON-BCON;

    if (diff>0){
    var recipients1 = "shadeel...@gmail.com";
   
    var subject = 'TEST RUN!!! Rematics - Siemens!!! - Partnership Sheet Updates  [ ' +diff +" Rows Updated]";
    var body = 'Rows Added TODAY = '+diff;

    MailApp.sendEmail(recipients1, subject, body);
   
    }
  } catch (f)  {
    Logger.log(f.toString());
   
  }

}

function Lastrow(shtid) {
Logger.log("sheet="+shtid);
var ss = SpreadsheetApp.openById(shtid)
var sh = ss.getSheetByName('Partnership')
var lrow = sh.getLastRow();
var Avals = sh.getRange("B1:B"+lrow).getValues();
var Alast  = lrow - Avals.reverse().findIndex(c=>c[0]!='');

Logger.log("lrow"+lrow+" =Avals  "+Avals+ "Alast="+Alast);
return Alast;
}
Reply all
Reply to author
Forward
0 new messages