Skip to content Skip to sidebar Skip to footer

Throw Custom Timeout Exception

I have a Google Apps Script web app ('Web App') that executes as the user, then calls individual functions from another Apps Script project ('API Executable') via the Apps Script A

Solution 1:

I ended up using the '''catch()''' block to throw an exception back to the client side and handle it there.

Google Apps Script:

functionexecuteAsMe(functionName, paramsArray) {
  try {
    console.log('Using Apps Script API to call function ' + functionName.toString() + ' with parameter(s) ' + paramsArray.toString());

    var url = 'https://script.googleapis.com/v1/scripts/Mq71nLXJPX95eVDFPW2DJzcB61X_XfA8E:run';

    var payload = JSON.stringify({"function": functionName, "parameters": paramsArray, "devMode": true})

    var params = {method:"POST",
                  headers: {Authorization: 'Bearer ' + getAppsScriptService().getAccessToken()},
                  payload:payload,
                  contentType:"application/json",
                  muteHttpExceptions:true};

    var results = UrlFetchApp.fetch(url, params);
    var jsonResponse = JSON.parse(results).response;
    if (jsonResponse == undefined) {
      var jsonResults = undefined;
    } else {
      var jsonResults = jsonResponse.result;
    }
    return jsonResults;
  } catch(error) {
    console.log('error = ' + error);
    if (error.toString().indexOf('Timeout') > 0) {
      console.log('Throwing new error');
      thrownewError('timeout');
    } else {
      thrownewError('unknown');
    }
  } finally {
  }
}

Client-side Javascript (a simplified version):

functioncreateMcs() {
      var userFolder = getDataFromHtml().userFolder;    

      google.script.run
        .withSuccessHandler(createMcsSuccess)
        .withFailureHandler(createMcsFailure)
        .withUserObject(userFolder)
        .executeAsMe('createMasterCombinedSchedule', [userFolder]);
    }

    functioncreateMcsSuccess(mcsParameter) {
      if (mcsParameter == undefined) {
        simpleErrorModal.style.display = "block"; // A generic error message
      } else {
        document.getElementById("simpleAlertHeaderDiv").innerHTML = 'Master Combined Schedule Created Successfully';
        document.getElementById("simpleAlertBodyDiv").innerHTML = 'Your Master Combined Schedule was created successfully. Click <a href="' + mcsParameter + '" target="_blank">here</a> to view.';
        simpleAlertModal.style.display = "block";
      }
    }

    functioncreateMcsFailure(mcsError, userFolder, counter) { // The exception I threw will activate this functionif (!counter) { // Added a counter to increment every time checkForCreatedMcs() runs so it doesn't run indefinitelyvar counter = 0;
      }
      if (mcsError.message == 'Error: timeout' && counter < 5) { // If timeout error, wait 10s and look for MCS URLwindow.setTimeout(checkForCreatedMcs(mcsError, userFolder, counter), 10000);
      } elseif (mcsError.message == 'Error: timeout' && counter == 5) { // If it hasn't worked after 5 tries, show generic error message
        simpleErrorModal.style.display = "block";
      } else { // For any error that's not a timeout exception, show generic error message
        simpleErrorModal.style.display = "block"; 
      }
    }

    functioncheckForCreatedMcs(mcsError, userFolder, counter) {
      counter++;
      google.script.run
        .withSuccessHandler(checkForCreatedMcsSuccess)
        .withUserObject([mcsError, userFolder, counter])
        .executeAsMe('checkIfMcsExists', [userFolder]); // checkIfMcsExists() is a pre-existing function in my API Executable project I had already used elsewhere      
    }

    functioncheckForCreatedMcsSuccess(mcsExistsParameter, params) {
      var mcsError = params[0];
      var userFolder = params[1];
      var counter = params[2];
      if (mcsExistsParameter == undefined) { // If function returns undefined, show generic error message
        simpleErrorModal.style.display = "block";
      } elseif (mcsExistsParameter == false) { // If function returns false, wait 10s and try againcreateMcsFailure(mcsError, userFolder, counter);
      } else { // If function returns URL, show success modal with linkdocument.getElementById("simpleAlertHeaderDiv").innerHTML = 'Master Combined Schedule Created Successfully';
        document.getElementById("simpleAlertBodyDiv").innerHTML = 'Your Master Combined Schedule was created successfully. Click <a href="' + mcsExistsParameter + '" target="_blank">here</a> to view.';
        simpleAlertModal.style.display = "block";
      }
    }

I am sure there has to be a tidier/less complex way to do this, but this worked!

Post a Comment for "Throw Custom Timeout Exception"