Handle 404 errors in UrlFetchApp.fetch()

2019-04-12 20:47发布

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

This is the code I have:

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;
  }
}

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?

Thank you!

--- EDIT ---

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;
  }
}

1条回答
啃猪蹄的小仙女
2楼-- · 2019-04-12 21:33

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");
  }
}
查看更多
登录 后发表回答