Home > Mobile >  return in catch block fails to be executed
return in catch block fails to be executed

Time:07-17

Basic example that throws an error because tl was not specified:

function allmatches() {
  SpreadsheetApp.getActive().getSheetByName('data').getRange('A1').setValue(tl)
}

And to know if there were any errors in the execution in the Web App, I added a try catch:

function doGet(e) {
  const lock = LockService.getDocumentLock();
  if (lock.tryLock(360000)) {
    try {
      var okgo = e.parameter.okgo;
      allmatches();
    } catch (e) {
      lock.releaseLock();
      return ContentService.createTextOutput('Error!');
    } finally {
      lock.releaseLock();
      return ContentService.createTextOutput('Ok!');
    }
  } else {
    return ContentService.createTextOutput('Timeout!');
  }
}

I call this Web App by Python and in theory the answer should be Error!:

import requests

okgo = 'go'
webAppsUrl = "https://script.google.com/macros/s/XXXXXXXXXX/exec"
url = webAppsUrl   "?okgo="   okgo
web_app_response = requests.get(url)
print(web_app_response.text)

But the response is:

Ok!

What am I missing?

Add, when run without web app it goes into catch:

function test() {
    try {
      allmatches();
    } catch (e) {
      Logger.log(e)
    }
}

Output:

ReferenceError: tl is not defined

CodePudding user response:

As you can see by the following examples the finally block is run regardless if an error occurs or not. So in the case of the OP ContentService.createTextOutput('Error!'); is quickly replaced by ContentService.createTextOutput('Ok!'); and the user is unaware of the error.

function testTry() {
  try {
    let x = a;
    console.log(x);
  }
  catch(err) {
    console.log(err);
  }
  finally {
    console.log("finally");
  }
}

7:52:56 AM  Notice  Execution started
7:52:58 AM  Info    [ReferenceError: a is not defined]
7:52:58 AM  Info    finally
7:52:57 AM  Notice  Execution completed

function testTry() {
  try {
    let x = 1;
    console.log(x);
  }
  catch(err) {
    console.log(err);
  }
  finally {
    console.log("finally");
  }
}

7:54:37 AM  Notice  Execution started
7:54:38 AM  Info    1
7:54:38 AM  Info    finally
7:54:38 AM  Notice  Execution completed
  • Related