Search code examples
google-apps-scripterror-handlingweb-applications

try/catch error handling in web app


I noticed that when an error is thrown in a try/catch block within a Google Apps Script, Logger.log(e instanceof Error) returns true. But, when that same object is passed back to the client in the catch statement, it logs false.

GAS sample

function isValid() {
  return false
}

function testing() {
  try {
    if(!isValid()) { throw new Error("failure") }
    return "success"
  } catch(e) {
    Logger.log(e instanceof Error) // true
    return e // false in the client when tested with console.log(e instanceof Error)
  }
}

client

function foo() {
 google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).testing();
}

function onSuccess(e) {
  console.log(e instanceof Error) // false
  console.log(e) // null
}

function onFailure(e) {
  console.log(e instanceof Error) // no result
}

Is there a better way to test for an error returned from the script file?


Solution

  • From the client side, you use a .withFailureHandler(...) when calling the .run.myFunction() code. The failure handler is a function in your client side code that will be called if an exception (i.e. error) is thrown in your server-side code and not handled.

    Failure handlers will only be called if an exception is thrown. Otherwise, the success handler receives the server-side function's return value.

    .gs

    function myFn() {
      try {
        throw new Error("failure");
      }
      catch (e) {
        Logger.log(e);
        // Must rethrow to activate the client's FailureHandler function.
        throw e;
      }
      return "success"
    }
    

    .html

    function foo() {
      google.script.run.withFailureHandler(logError).withSuccessHandler(useReturnValue).myFn();
    }
    function logError(error) {
      console.log(error);
    }
    function useReturnValue(value) {
      // do stuff
    }
    

    In the client side console, you will see the error get logged.