Flame of udun
Flame of udun

Reputation: 2237

Can't access variable inside catch javascript

I declared a variable aliasError in a function and tried to store the error value caught using a try/catch block in that variable.

However I can't access that variable inside the catch block. I can access it in the try block and outside the try/catch block though.

Not sure if this a javascript or google-apps-script issue.

Here is a snippet:

function onFormSubmit(e)
{
  //...........//
  var aliasError;     // VARIABLE DECLARED


  // CREATE UPDATES IN GMAIL
  // 1. ALIASES
  // do we need a new account and if not, then the latest account
  var conciergeStatus = getConcierge();
  var newAccountNeeded;
  parseInt(conciergeStatus[0]) == 1 ? newAccountNeeded = true : newAccountNeeded = false;
  if(newAccountNeeded)
  {
    //..........//
  }
  else
  {
      var conciergeAccount = conciergeStatus[2];
      conciergeAccLog = conciergeAccount;
      Logger.log("*******************UPDATING CONCIERGE ACCOUNT************************");
      Logger.log(conciergeAccount["name"]);
      var aliases = conciergeAccount["aliases"];
      var userEmail = conciergeAccount["primaryEmail"];
      conciergeEmail = userEmail;
      var alias = {
      alias: responseMap["Alias email"]
      };
      Logger.log(userEmail);
      Logger.log(alias);


      aliasError = "No error"; // VARIABLE ACCESSED SUCCESSFULLY
      try
      {
      aliasError = "No error"; // VARIABLE ACCESSED SUCCESSFULLY
      AdminDirectory.Users.Aliases.insert(alias, userEmail);
      }
      catch(err)
      {
      aliasError = err; // VARIABLE ACCESS FAILED
      }
      Logger.log(aliases);
  }
    //..............//
}

How do I overcome this issue?

Upvotes: 1

Views: 4291

Answers (2)

dds
dds

Reputation: 83

Actually you can't. It is not a google app script editor or runtime issue, it is part of the Javascript spec. The catch block creates a new variable declaration environment (a new scope) where the only variable accessible within the catch block is the exception itself that comes as parameter of the catch. See here for the full ECMA spec https://www.ecma-international.org/ecma-262/10.0/index.html#sec-variablestatements-in-catch-blocks

Upvotes: 2

Vladimir M
Vladimir M

Reputation: 4489

If you will try to replace assignment line in catch statement with the console.log(aliasError) with that change the color? Cause the following code would show variable to be very well accessible in the catch statement:

function x(){
var aliasError = 10;
     try
      {
      aliasError = "No error"; // VARIABLE ACCESSED SUCCESSFULLY
      xx=yy;
      }
      catch(err)
      {
      aliasError = err; // VARIABLE ACCESS FAILED
      }
console.log(aliasError)
}

x();

Having a state resolution in editor is not a trivial task. I have never used google editor, but I would not put 100% trust in editor's code analysis.

Upvotes: 1

Related Questions