google-apps-script - 如何在 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")
吗?如果有权限错误,是否处理?如何在服务器端生成错误,以便在客户端正确处理?
解决方案
确实文档没有明确指定它,但是您可以同时实现成功和错误处理程序
样本:
<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 会输出:
推荐阅读
- reactjs - 如何使用打字稿工作和定义对象的基础属性
- php - 向多个收件人发送消息的 Mailgun 呼叫未返回给呼叫者 - 提供的示例
- r - ggplot2 barplot,其中分类变量具有三个分量
- asp.net-core - 如何将“一般信息”部分添加到 NSwag 生成的 API 文档网站?
- mysql - 我有一个包含不同部分的短语,我需要使用 SQL 将它们拆分,三个不是短语中的分隔符
- c++ - 一个结构的所有对象的条件语句而不写每一个?
- android - 将高程(阴影)添加到 ExtendedFloatingActionButton
- python - 使用 pyelftools 抓取程序头信息
- json - Microsoft Bot Framework API 创建与多个成员的对话
- python - 传递默认参数的pythonic方式是什么?