Debugging your script

Logging the values of variables at a few points is essential when testing and debugging your code. The Logger class is a helpful tool to do this and has a few methods that are essential to debug your code.

Update the showDialog function as shown here:

function showDialog() {
  var ui = DocumentApp.getUi();

  var response = ui.prompt(
      'Greeting', 'Will you enter your name below?', ui.ButtonSet.YES_NO
  );

  if (response.getSelectedButton() == ui.Button.YES) {
    Logger.log('Your name is %s.', response.getResponseText());
  } else if (response.getSelectedButton() == ui.Button.NO) {
    Logger.log('You clicked \'NO\' button');
  } else {
    Logger.log('You closed the dialog.');
  }
}

Run the showDialog function as usual from the Add-ons menu. Do anything, for example, enter your name and click on Yes or No or close the dialog.

Now within the script editor, press Ctrl + Enter (Windows) or Command + Enter (Mac) or from the View menu, select Logs, then you can see the logged text with a timestamp as shown here:

For a more detailed study of the Logger future, create the function debug as shown here:

function debug(){
  var square = 0;
  for(var i = 0; i < 10; i++){
    square = i * i;
    Logger.log(square);
  }
}

Run the debug function and see the Logger result as shown here:

In addition to logging, you can use the debug feature of the editor. In the editor, you set break points at one or more lines. To do so, click once on the line number on which you want to set a break point. A red dot will be toggled just on the left-hand side of the line number, as shown here:

Select the debug function that you want to debug in the Select function selector if it is not already selected. Click on the Debug button (shown as an insect) to the left of the function selector. The function is executed up to the break point and then pauses. The edit window is split horizontally and shows the object and its values in the bottom part of the window as shown here:

Click on the Continue debugging button to see the values on every cycle of the for loop.

Tip

You can experiment with the other features such as step into, step over, and step out.

To exit the debugging session, click on the Stop debugging button and remember to remove (toggle) all the break points.