Waqar Ahmad
Waqar Ahmad

Reputation: 3730

try catch do not work with app.getElementById in handler functions

I am developing an app where I thought to use try catch blocks in handler function but it is giving error "Error encountered: An unexpected error occurred". Code seems right but it is not working. The error is happening only in case of app.getElementById('elementId') in try block

Here is my code.

function doGet(e) {
  var app = UiApp.createApplication();
  var hPanel = app.createHorizontalPanel();
  app.add(hPanel);
  var handler = app.createServerHandler('handleOpenClose_');
  var btn1 = app.createButton('Open Item').setId('openBtn').addClickHandler(handler);
  var btn2 = app.createButton('Close Item').setId('closeBtn').addClickHandler(handler);
  hPanel.add(btn1).add(btn2);
  return app;
}

function handleOpenClose_(e){
  var source = e.parameter.source;
  var app = UiApp.getActiveApplication();
  var itemPanel;
  try{//check if itempanel exists
    var itemPanel = app.getElementById('itemPanel');
  }
  catch(e){// if it does not exists, create it
    var itemPanel = app.createVerticalPanel().setId('itemPanel');
    app.add(itemPanel);
    for(var i=0; i<10; i++){
      itemPanel.add(app.createLabel('Item '+i));
    }
  }

  if(source == 'openBtn'){itemPanel.setVisible(true)}
  else if(source == 'closeBtn'){itemPanel.setVisible(false)}

  return app;
}

I know there are other ways to achieve the same but I thought to share this observation with google-apps-script community. Let me know if my observation is correct. If it is a bug, I'd like to post it in issue tracker.

Upvotes: 1

Views: 184

Answers (1)

Srik
Srik

Reputation: 7965

This issue has been reported to Google quite a while back as Issue 592. Unfortunately, when an item with a given id doesn't exist, GAS shows an Unexpected error alert box instead of throwing an exception to the code.

Upvotes: 1

Related Questions