处理UrlFetchApp.fetch()中的404错误 [英] Handle 404 errors in UrlFetchApp.fetch()

查看:94
本文介绍了处理UrlFetchApp.fetch()中的404错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Google Spreadsheets中创建扩展名,并且试图处理urlFetch()可能出现的404错误.现在,它只是在电子表格的顶部显示一个弹出窗口,如下所示:

I'm creating a extension in Google Spreadsheets and I'm trying to handle the 404 error that the urlFetch() might give. Right now it's just showing a popup at the top of the spreadsheet like this:

http://i.stack.imgur.com/fvCPC.png

这是我的代码:

function doTestAPICall() {
  var headers = {
    'Authorization': 'Basic ' + Utilities.base64Encode(user + "/token:" + token)
  };
  var url = "https://" + subdomain + ".domain.com/api/v2/users/me.json";
  var options = {
    'contentType': 'application/json',
    'method': 'get',
    'headers': headers
  };
  var response = UrlFetchApp.fetch(url, options);
  if(response.getResponseCode() == 200){
    var json = response.getContent();
    var data = JSON.parse(json);
    if(data.user.email != user){
      return false;
    } else {
      //User was correctly authenticated
      return true;
    } 
  }else{
    return false;
  }
}

但是,该函数永远不会访问response.getResponseCode(),因为它已经在UrlFetchApp.fetch函数上失败了.关于如何处理此问题的任何想法/建议?

However, the function never gets to response.getResponseCode() because it fails already on the UrlFetchApp.fetch function. Any ideas/suggestions on how can I handle this?

谢谢!

-编辑--

按照阿米特(Amit)的建议,在UrlFetchApp选项中添加MutantHttpExceptions解决了该问题.

As per Amit's suggestion adding muteHttpExceptions in the UrlFetchApp options solved the issue.

代码现在看起来像这样:

Code looks now like this:

function doTestAPICall() {
  var headers = {
    'Authorization': 'Basic ' + Utilities.base64Encode(user + "/token:" + token)
  };
  var url = "https://" + subdomain + ".domain.com/api/v2/users/me.json";
  var options = {
    'contentType': 'application/json',
    'method': 'get',
    'headers': headers,
    'muteHttpExceptions': true
  };
  var response = UrlFetchApp.fetch(url, options);
  if(response.getResponseCode() == 200){
    var json = response.getContentText();
    var data = JSON.parse(json);
    if(data.user.email != user){
      return false;
    } else {
      //User was correctly authenticated
      return true;
    } 
  }else{
    return false;
  }
}

推荐答案

您可以在HTTP请求中将MutantHttpExceptions设置为true,以消除这些错误.

You can set muteHttpExceptions to true in the HTTP request to suppress these errors.

function fetchPage() {
  var response = UrlFetchApp.fetch("http://ctrlq.org/404", {muteHttpExceptions: true});
  if (response.getResponseCode() == 404) {
    Logger.log("Web page not found");
  }
}

这篇关于处理UrlFetchApp.fetch()中的404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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