Check if the execution is running in debug mode

Viewed 459

Is there a way to check if Google Apps Script is running in debug mode ?

For an example, I have a script for which I use prompt but, in debug mode, I want to set predefined values for these prompt.

2 Answers

Try debugging myfunc() with debugMyFunc();

function debugMyFunc() {
  myfunc('debug');
}

function myfunc(mode) {
  var mode=mode||'run';
}

Problem

If you are looking for an analog of a debug environment, then no, there is no dedicated way - the only mode is production (although some services like CardService and UrlFetchApp do have debug methods).

Workaround

The closest thing to an environment would be using PropertiesService to store, update and retrieve script / user properties. You can persist the settings per user or, which is closer to what an environment variable is, per script and use them as needed.

Therefore, to check whether you run in a debug mode, you can load the property from store (preferrably at startup to reduce property reads / writes), check for something like mode, and then pass the result around + change and persist as needed.

A simple example:

/**
 * @returns {object}
 */
function getEnvironment() {
  const store = PropertiesService.getScriptProperties();
  const env = JSON.parse(store.getProperty("env") || "{}");

  env.Modes = Object.freeze({
    Debug : 1,
    Prod : 2
  });

  return env;
}

Then, in your main script:

function onOpen() {

  let { mode, Modes } = getEnvironment();

  if(mode === Modes.Debug) {
    //do something in debug
  }

  mode = Modes.Prod;

  //continue in production
}

References

  1. PropertiesService reference
Related