在Google脚本中尝试/捕获HTTP响应的最佳方法 [英] Best way to Try/Catch HTTP response in Google Script

查看:39
本文介绍了在Google脚本中尝试/捕获HTTP响应的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然不熟悉JavaScript和Google Apps脚本,这是我第一次尝试使用"Try/Catch"语句.

I'm still new to JavaScript and Google apps script, and this is the first time I'm trying to use a 'Try/Catch' statement.

我正在运行连接到页面的脚本.它在大多数情况下都可以正常连接,但偶尔也不会响应并抛出http错误(或者,响应为空).如果收到错误代码,我想尝试/捕获此响应以使其第二次运行,但是我不确定100%知道我的语法,因为无论我如何格式化,它都不会抛出异常,或总是扔它.

I'm running a script that connects to a page. It connects most of the time without issue, but occasionally it won't respond and throw a http error (Or, the response will be empty). I want to try/catch this response to have it run a second time if I get an error code, but I'm not 100% sure I understand the syntax, because no matter how I format it, It either never throws the exception, or always throws it.

以下是我正在尝试的一些示例代码:

Here is some sample code I've been experimenting with:

function myFunction() {
  var response =  UrlFetchApp.fetch("google.com"); 
  Logger.log('Response Code: ' + response.getResponseCode());

try {if(response.getResponseCode() === 200);
} catch (err) {
    throw 'Page connected';
}
}

如果我可以解决这个问题,那么我可以确定其余的内容.但是,即使日志显示我得到200的HTTP响应,它也不会抛出页面已连接"错误.

If I can get this to work, I'm sure I can figure out the rest. However, even though the log shows me I get a HTTP response of 200, it never throws the error 'Page connected'.

如果有人可以指导我:

1)这是实现我想要的目标的正确方法,还是尝试/捕获"其他功能?2)正确的语法.

1) Is this the correct method to achieve what I want, or is Try/Catch for something else? 2) The correct syntax.

我将非常感谢.

推荐答案

getResponseCode 不会引发异常,但是 fetch 会引发异常,因此请将其包含在您的 try 块:

getResponseCode does not throw an exception but fetch does throw an exception, so include it inside your try block:

function myFunction() {
  try {
    var response =  UrlFetchApp.fetch("google.com"); 
    Logger.log('Response Code: ' + response.getResponseCode());

    if(response.getResponseCode() === 200) {
      // something
    }
  } catch (err) {
      // handle the error here
  }
}

这篇关于在Google脚本中尝试/捕获HTTP响应的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆