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;
}
}
You can set muteHttpExceptions to true in the HTTP request to suppress these errors.