我正在Google Spreadsheets中创建扩展程序,我正在尝试处理urlFetch()可能提供的404错误。现在它只是在电子表格的顶部显示一个弹出窗口,如下所示:
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函数上失败了。关于如何处理这个问题的任何想法/建议?
谢谢!
---编辑---
根据Amit的建议,在UrlFetchApp选项中添加muteHttpExceptions解决了这个问题。
代码现在看起来像这样:
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;
}
}
答案 0 :(得分:6)
您可以在HTTP请求中将muteHttpExceptions设置为true以抑制这些错误。
function fetchPage() {
var response = UrlFetchApp.fetch("http://ctrlq.org/404", {muteHttpExceptions: true});
if (response.getResponseCode() == 404) {
Logger.log("Web page not found");
}
}