简体   繁体   English

Google Apps脚本Web应用程序中的异常处理

[英]Exception handling in google apps script web apps

I want to write try catch error handling mechanism in google apps script. 我想在Google Apps脚本中编写try catch错误处理机制。 I've deployed a web app and i want that if by any means any part of the functions written in script failed to execute, i want to put custom message on browser screen. 我已经部署了一个Web应用程序,我希望通过脚本编写的功能的任何部分执行失败,我希望将自定义消息显示在浏览器屏幕上。

Lets go with program... First method which will get executed 让我们一起去程序...将要执行的第一个方法

function doGet(e){
  //Calling method
  methodCall();
  return HtmlService.createHtmlOutputFromFile('success');
}

Now lets say, inside method call there is some line which is error prone which will cause error if supply with improper inputs. 现在说,在方法调用内部,有一些容易出错的行,如果提供的输入不正确,则会导致错误。 So how could i capture this error and displaying custom error message on browser instead of success file's content. 因此,我该如何捕获此错误并在浏览器上显示自定义错误消息,而不是成功文件的内容。

function methodCall(){
   //Call to some Google API
  try{
    DriveApp.getFiles();
  }catch(err){
    return HtmlService.createHtmlOutput("<p>Custom error message</p>"); 
  } 
}

So by the end of loading the page, user can see the custom error message on his browser. 因此,在加载页面结束时,用户可以在其浏览器上看到自定义错误消息。

I'm not too familiar with Web Apps nor have I tested the code below but it should work or at least give you something to go on. 我对Web Apps不太熟悉,也没有测试下面的代码,但是它应该可以工作,或者至少可以为您提供一些帮助。

A couple of things. 有几件事。

  1. Create a variable to store the value returned from the methodCall() function. 创建一个变量来存储从methodCall()函数返回的值。

  2. In the methodCall() function you cant return the HtmlService, instead if there is an error return the message that you want to output. methodCall()函数中,您不能返回HtmlService,而是如果出现错误,则返回要输出的消息。 If there is no error the return nothing. 如果没有错误,则不返回任何内容。

  3. In your doGet(e) check var response if nothing has been returned it will be false if anything has been returned it will be true then return your Html in the doGet. 在您的doGet(e)检查var response如果未返回任何内容,则返回false,如果已返回任何内容,则返回true,然后在doGet中返回您的HTML。

  4. In your code you have createHtmlOutputFromFile('success'); 在您的代码中,您具有createHtmlOutputFromFile('success'); should this be createHtmlOutput('success') . 应该是createHtmlOutput('success')

      function doGet(e){ //Calling method var response = methodCall(); if(response){ return HtmlService.createHtmlOutput(response); } else { return HtmlService.createHtmlOutputFromFile('success'); } function methodCall(){ //Call to some Google API try{ DriveApp.getFiles(); }catch(err){ return "<p>Custom error message</p>"; } return; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM