如何解决/处理偶尔出现的API 400错误

时间:2019-05-04 14:35:56

标签: google-apps-script

我有一个简单的脚本,该脚本每30分钟调用8个不同的API。这些API中只有一个API每两天返回一次400错误的请求错误,这似乎有些奇怪。谁能提出我可能在做错的事情,或者如果不是我的错,也许是一种简单的方法来重试失败的呼叫吗?

var hayurl = "https://api.naturalresources.wales/riverlevels/v1/all?Location=4016";

var hayheaders = {
  "contentType": "application/json",
  "headers": {"Ocp-Apim-Subscription-Key": "xxxxxxxxxxxx"}
};

var hayresponse = UrlFetchApp.fetch(hayurl, hayheaders);

在大多数情况下,它只是返回我想要的数据,但偶尔的失败却让我感到困惑!

1 个答案:

答案 0 :(得分:1)

如果您知道正确的响应码是什么,请mute HTTP exceptions并使用HTTPResponse.getResponseCode()进行检查。在下面的示例中,我假设正确的响应代码是200。

function getApiData() {
  var url = "https://api.naturalresources.wales/riverlevels/v1/all?Location=4016";
  var params = {
    "contentType": "application/json",
    "headers": {"Ocp-Apim-Subscription-Key": "xxxxxxxxxxxx"},
    "muteHttpExceptions": true // Without this, you'll still get an error
  };
  var maximumAttempts = 5; // Set a limit of retry attempts to prevent an infinite loop
  var attemptCount = 0;
  do { // Execute this block
    attemptCount++; // This needs to be BEFORE the request in case of failure, otherwise it will never increment
    var response = UrlFetchApp.fetch(url, params);
  } while (response.getResponseCode() != 200 && attemptCount < maximumAttempts); // If not 200, execute the block again
  return response;
}

或者,使用try...catch语句。如果使用此方法,则既不需要忽略HTTP异常,也不需要知道确切的成功响应代码。通过禁用muteHttpExceptions(默认情况下处于禁用状态),UrlFetchApp.fetch()调用将引发您一直看到的错误。我们指望发生这种情况,因为错误将被捕获,然后触发重试尝试。这可能是一个更好的策略,因为它会捕获其他错误,而我的第一种方法仅捕获响应代码不完全为200的非常具体的实例。

function getApiData() {
  var url = "https://api.naturalresources.wales/riverlevels/v1/all?Location=4016";
  var params = {
    "contentType": "application/json",
    "headers": {"Ocp-Apim-Subscription-Key": "xxxxxxxxxxxx"}
  };
  var maximumAttempts = 5; // Set a limit of retry attempts to prevent an infinite loop
  var attemptCount = 0;
  do { // Execute this block
    var isErrored = false; // Reset to false at the start of each new iteration
    try {
      attemptCount++; // This needs to be BEFORE the request in case of failure, otherwise it will never increment
      var response = UrlFetchApp.fetch(url, params);
    } catch (err) {
      isErrored = true; // If there was an error, set to true so the script will try again
    }
  } while (isErrored && attemptCount < maximumAttempts); // If isErrored, execute the block again
  return response;
}

以防万一您不熟悉循环逻辑,我使用的是do...while语句,该语句将首先执行代码块 ,然后检查条件以查看该代码是否应该继续执行。