So this function gets a folder, gets the subfolders, pushes some information to an array and then pastes the array into my spreadsheet.
It fails at a weird point about 2-5% of the time, and the attempts I have made to error catch it earlier just don't work. why/how!
function getFileCount(gdrive,level,fullpath){
var folder = DriveApp.getFolderById(gdrive);
var fileCount = 0;
//append the subfolders to the sheet
var folders = folder.getFolders();
var result = [];
while (folders.hasNext()){
var folder = folders.next();
var path = fullpath + " > " +folder.getName();
result.push([(level+1),folder.getId(), path,"?"]);
}
if (result == []) return fileCount;
if (result == undefined) {console.log("Why the hell is it undefined?"+folder.getName()); return fileCount;}
var sh = SpreadsheetApp.getActiveSpreadsheet();
var ss = sh.getSheetByName("FoldersPlusCounts");
var end = ss.getLastRow()+1;
try{ss.getRange(end, 1,result.length, result[0].length).setValues(result);}catch(e){console.log(e+" "+gdrive+" ["+result+"]");return -1;}
if (result.length > 0) SpreadsheetApp.flush();
return fileCount;
}
the try catch statement is where it fails saying:
TypeError: Cannot read property 'length' of undefined 1dmDV2qdnU2Qqrg6mr-sxD8JaQncTUNqn []
This doesn't occur every time the folder has no files, or every time it has no folders, I don't think.
So how can result sometimes be undefined, when it is clearly defined as result = [], and if it is undefined, why isn't it being captured by the "if result == undefined" line?
Some lines removed for clarity (just the file counting stuff), I wasn't using result up in that part anyway.