首页 > 解决方案 > 如何在 Google Apps Script Webapp 上同时处理错误和成功

问题描述

我想知道与 Google Apps Script Webapps 的客户端-服务器通信是如何工作的。在 html 页面中,我调用我的函数

google.script.run.doSomething();

我可以添加一个

withFailureHandler(onFailure);

或者

withSuccessHandler(onSuccess)但我不能同时添加..

因此,当我想调用服务器端函数时,我通常想处理 UI 中的响应——如果它是成功而不是失败,对吧?但我想同时处理这两个问题吗?那么为什么我必须在其中之一之间进行选择呢?

另一个问题是,我找不到任何有关您在服务器端可能遇到的实际错误的信息,以便您withFailureHandler(onFailure);可以处理它们。我可以做一个throw new Error("everything is broken - tell that the user")吗?如果有权限错误,是否处理?如何在服务器端生成错误,以便在客户端正确处理?

标签: google-apps-scriptweb-applications

解决方案


确实文档没有明确指定它,但是您可以同时实现成功和错误处理程序

样本:

<html>
  <head>
   <base target="_top">
    <script>
      google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).getUnreadEmails();
     function onSuccess(numUnread) {
       var div = document.getElementById('output');
       div.innerHTML = 'You have ' + numUnread  + ' unread messages in your Gmail inbox.';
     }
     function onFailure(error) {
       var div = document.getElementById('output');
       div.innerHTML = "ERROR: " + error.message;
     }
    </script>
  </head>
  <body>
    <div id="output"></div>
  </body>
</html>

更新

要根据文档样本模拟故障,请更改工作code.gs部分

function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index');
}

function getUnreadEmails() {
  return GmailApp.gotInboxUnreadCount();
}

function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index');
}

function getUnreadEmails() {
  return GMailApp.gotInboxUnreadCount();
}

部署 WebApp 后,html 会输出:

在此处输入图像描述


推荐阅读