Sunday, June 6, 2010

Debugging Event Handlers

Finding errors in code can be very hard, and doing so without any clues is very very hard. Unfortunately that's the potential problem facing everyone using the new installable event handlers.  The scripts that we write to handle events aren't initiated directly by a user at a screen, so there's no immediate place to report error messages and problems.  As a result we're frequently baffled as to why our scripts don't work as expected!

Here's a simple trick for catching errors and emailing them to yourself.  We're relying on a very nice feature of JavaScript called Exception Handling, and you can learn more about it here.  We take the existing event handler:

function myFunc(){
  // put your event handling code here.
}


and simply wrap it in a try/catch block:

function myFunc(){
  try{
    // put your event handling code here.
  catch(error){
    MailApp.sendEmail("me@example.com"

                      "Error Handling Event!"
                      "Error: " error);
  }     
}


Now every time your Event Handling code breaks, you'll get an email telling you all about it.

6 comments:

  1. What would be great is if there could be offline logging. Currently, we can set our own entries into the log, but only when directly running and testing.

    What if there were a persistently stored log, that could be written to as the scripts are run via events or even directly by other users, then the developer of the script could reference this log. Rather than getting bombarded by emails using this method.

    ReplyDelete
  2. hi!~~leave you a message to say hello, and thanks for your share!.........................

    ReplyDelete
  3. @Bob
    try this:

    function errorTest() {
    try{
    var anError = SpreadsheetApp.LOOKanERROR();
    //...more of your code...
    }catch(error){
    var errorSheet = SpreadsheetApp.openById('YourSheetID').getSheetByName('errors');
    lastRow = errorSheet.getLastRow();
    var cell = errorSheet.getRange('a1').offset(lastRow, 0);
    cell.setValue(error);
    }
    }​

    ReplyDelete
  4. I think that could faster this code:
    SpreadsheetApp.openById("spreadsheetKey").getSheetByName("MySheet").appendRow("Error"+MyError);

    ReplyDelete