0

I want to create a directory in the drive if it doesn't already exist.

function CreateDirectory() {
  var folderName="Example";
  var Directory;
  var fi = DriveApp.getFoldersByName(folderName);
  if (fi.hasNext()) {
    Directory = fi.next();
  } else {
    Directory = DriveApp.createFolder(folderName);
  }
}

The function stops when the condition is reached:

Sorry, a server error has occurred. Please wait a bit and try again.

What is the problem and how can it be fixed?

TheMaster
  • 45,448
  • 6
  • 62
  • 85
  • 1
    There is nothing wrong with your code. Google can not offer 100% service availability. What you can do is to use a a try-catch statement and within the catch brackets include a code to delay this process (a time trigger or sleep or something like that) – Marios Oct 04 '20 at 23:48
  • As the error message said, wayit a bit and try again. – Rubén Oct 05 '20 at 01:12
  • Hi @Marios , could you formalise your comment into an answer to this post so that other users encountering similar error messages can easily find the solution? Thanks ! – Mateo Randwolf Oct 05 '20 at 10:08
  • Does this answer your question? https://stackoverflow.com/questions/64079595/i-have-enabled-v8-runtime-but-i-get-an-error-trying-save-were-sorry-a-serve – TheMaster Oct 06 '20 at 14:43
  • Yes, if I copy it to another project, it works. I originally copied it here from another project and it doesn't work here. Whichever project I want to use the code in is not my property, I am just an editor. Therefore, I can't put it into a new project (or I don't know how I could solve it) However, I don’t think I would need to create a new project for this and copy thousands of rows and then re-authorize multiple accounts. – Gábor Raczky Oct 06 '20 at 19:26
  • @GáborRaczky Thing is server errors are usually beyond your control as the server itself is beyond your control. Even if there's something you did that caused the server error, it's hard to pinpoint what exactly you did that caused the error. – TheMaster Oct 06 '20 at 19:32

2 Answers2

1

There is nothing wrong with your code.

Google can not guarantee 100% service availability.

Explanation:

The error tells you that you need to wait a little bit before your execute that function again.

A potential workaround solution would be to use a try...catch statement and within the catch brackets include a code to automatically execute the function after some time.

For example, you can create a time-driven trigger that executes CreateDirectory() after some time (e.g. 1 minute) if the function failed the first time.


Solution:

In the following solution the logic is to manually execute the toRun() function. The latter will try to execute CreateDirectory(). If an error occurs, it will create a time-driven trigger that will execute CreateDirectory() after a minute (modify that to your needs). The clearTrigger() function is responsible for clearing all the previous triggers (if there are any) that are created because of that code.

function toRun(){

  try{
    CreateDirectory();
  }
  
  catch (e){
    
     clearTrigger(); // clear previous created triggers
     ScriptApp.newTrigger("CreateDirectory") 
     .timeBased()
     .after(1 * 60 * 1000) // execute CreateDirectory after 1 minute
     .create();
  } 
 
}

function CreateDirectory() {
  var folderName="Example";
  var Directory;
  var fi = DriveApp.getFoldersByName(folderName);
  if (fi.hasNext()) {
    Directory = fi.next();
  } else {
    Directory = DriveApp.createFolder(folderName);
  }
}

function clearTrigger(){

var triggers = ScriptApp.getProjectTriggers();
for (var i = 0; i < triggers.length; i++) {
  if (triggers[i].getHandlerFunction() == "CreateDirectory") {
    ScriptApp.deleteTrigger(triggers[i]);
  }
}
}
Marios
  • 26,333
  • 8
  • 32
  • 52
  • Unfortunately, the solution is not good. I tried for hours at times, never running correctly. The problem always same: "if (fi.hasNext())" There is another google sheet, in it the same code always runs without error. Could there be some permission problem? – Gábor Raczky Oct 05 '20 at 20:14
1

Server errors might occur when you make requests. To solve these type of unexpected errors you can apply exponential backoff, a technique that basically tries to run the request you are asking for a number of times. If the request still gets an error like the one you are getting, then this technique catches this error and waits a certain amount of time before asking again for this request. This will avoid the network congestion causing the unexpected error.

In your example exponential backoff can be achieved using the following piece of code (it has self-explanatory comments):

// Function that implements exponential backoff
function myFuncion(){
  var folderName="Example";
  var Directory;
  
  var fi = DriveApp.getFoldersByName(folderName);

  // Try making the request 50 times (you can change this to n number of times)
  for(i=0;i<50;i++){
    try{
      if (fi.hasNext()) {
          Directory = fi.next();
      } else {
              Directory = DriveApp.createFolder(folderName);
             }
       break;
      // If successful you get out of the loop and run your function correctly
      // Otherwise wait for an exponential amount of time before making the request again
    }catch(e){
      Utilities.sleep((Math.pow(2,i)*1000) + (Math.round(Math.random() * 100)));
    }
    
  }
  Logger.log(Directory);
}

Reference:

Utilities.sleep()

Exponential backoff in Google Cloud

Exponential backoff

halfer
  • 19,824
  • 17
  • 99
  • 186
Mateo Randwolf
  • 2,823
  • 1
  • 6
  • 17
  • As I have already written, even if I run the code several times, it always gives an error. :( – Gábor Raczky Oct 24 '20 at 11:47
  • Are you still getting that server error message with my implementation? Are you still getting that error on this line of code ```if(fi.hasNext())```? Could you please log ```fi``` before you execute the line of code returning your error ```Logger.log(fi)```? – Mateo Randwolf Oct 26 '20 at 10:16
  • Yes, server error has occurred... Logger.log(fi) result: [20-10-27 14:51:02:373 CET] FolderIterator – Gábor Raczky Oct 27 '20 at 13:53
  • Hi! I have edited my answer, could you try with my updated code to see if you still get the same error? Thanks ! :D – Mateo Randwolf Oct 28 '20 at 08:14
  • Not working, fi.hasNext() always error. In another project working. I don't understand. :D – Gábor Raczky Oct 29 '20 at 10:37
  • Could it be possible for you to share with me the script (as long as it does not contain any sensitive information or you substitute it with non sensitive information) so that I can look further into it to figure out where this script might be failing? Thanks ! :D – Mateo Randwolf Oct 30 '20 at 08:46
  • The spreadsheet and script not mine, but I share document with you. I need your email address. I not found PM to you... – Gábor Raczky Oct 31 '20 at 10:04
  • No worries then, I thought the script was yours and therefore, visible to public. If you make a copy of your script and run the function do you encounter the same error? Is your script attached to any GCP project ? Could you see what you obtain before the error line if you run ```Logger.log(fi.next())```? Thanks ! :D – Mateo Randwolf Nov 02 '20 at 15:39
  • Ok, I create copy of script and run function. It's work, no error. Logger.log(fi.next()) equivalent under both run. How delete copy of project? – Gábor Raczky Nov 03 '20 at 16:59
  • What's the output of ```Loger.log(fi.next())``` ? To delete this copy just delete the script. – Mateo Randwolf Nov 04 '20 at 15:17
  • Logger.log(fi) result: [20-10-27 14:51:02:373 CET] FolderIterator – Gábor Raczky Nov 05 '20 at 18:16
  • Hi ! I have updated my answer to include a break I forgot to include on it but I dont thing it will change much of your current situation (just in case try it). Could you run with the following log and let me know what it says ```Logger.log(fi.next().getName())```? Also, do you know if this script is linked to any GCP project or bounded to any Spreadsheet/Docs/Slides/etc ? – Mateo Randwolf Nov 06 '20 at 08:26
  • Sorry, I spoiled it. So `Logger.log(fi)` result FolderIterator, but `Logger.log(fi.next())` already gives an error (Sorry, server error...). `Logger.log(fi.next().getName())` also error. Yes, script is connected only a Spreadsheet. – Gábor Raczky Nov 06 '20 at 18:05
  • I am sorry but I cannot reproduce the behaviour of that script. As the script belongs to someone else, if your client or you have G Suite you might want to contact the [G Suite Support team](https://support.google.com/a/answer/1047213?hl=en) as the problem seems to be bounded to your script. Otherwise you could ask the owner of the script for permission to include a public link to that script to this public forum so that other users like me can test and troubleshoot that specific script. – Mateo Randwolf Nov 09 '20 at 14:47