Handle Errors in Apps Script with Try and Catch

In previous posts I discussed simple debugging techniques involving logging errors and using the Script Editor’s built in debugger. A more elegant way to deal with code errors is to include code in your script to intercept the production of the error and deal with it appropriately. This is usually referred to as exception handling

To help work out what went wrong in a script, you can surround part of the code with a try-catch block. Here’s an example:

try {
   // your script code here
 } catch(e) {
   // if the script code throws an error,
   // do something with the error here
 }

The following example is a snippet of code that will grab information about an error and send you an email notification containing the text of the error message:

function myFunction(){
  try {
    // your script code here
  } catch (e) {
    MailApp.sendEmail("you@example.com", "Error report", e.message);
  }
}

The code attempts to execute the statements in the try{} block. If an error is thrown, the catch(e) statement will gather that error and apply it to the variable named in the argument you supplied to catch() (in this case e).

This variable has three properties you can access via code:

e.message       Human-readable description of the error
e.fileName     The value for the fileName property on the created Error object. Defaults to the name of the file containing the code that threw the error.
e.lineNumber    The value for the lineNumber property on the created Error object. Defaults to the line number containing the code that threw the error.

Here’s an example routine to test it:

function myFunction(){
  try {
    // your script code here
    var x = badFunction(); // this should create and error
  } catch (e) {
    MailApp.sendEmail("my.address@gmail.com", "Error report", 
      "\r\nMessage: " + e.message
      + "\r\nFile: " + e.fileName
      + "\r\nLine: " + e.lineNumber);
  }
}

Running the code produces no visible error; however, checking my Gmail Inbox:

Click image to enlarge

Click image to enlarge

Of course, you may not want to receive an email any time any user had an error condition in one of your scripts! That would get old pretty quickly. How about, instead, we record each error as a list in a spreadsheet with a particular ID?

try {
 // your script code here
} catch(e) {
 var errorSheet = SpreadsheetApp.openById('[ID]').getSheetByName('Errors');
 lastRow = errorSheet.getLastRow();
 var cell = errorSheet.getRange('A1');
 cell.offset(lastRow, 0).setValue(e.message);
 cell.offset(lastRow, 1).setValue(e.fileName);
 cell.offset(lastRow, 2).setValue(e.lineNumber);
}

And here’s the content of the spreadsheet after collecting a few error reports:

Click image to enlarge

Click image to enlarge