Skip to content

Instantly share code, notes, and snippets.

@dcvogi
Last active April 24, 2018 20:34
Show Gist options
  • Save dcvogi/aa88f5db5508cdabaef9f0eb7c251240 to your computer and use it in GitHub Desktop.
Save dcvogi/aa88f5db5508cdabaef9f0eb7c251240 to your computer and use it in GitHub Desktop.
Apps Scripts template to query data from Google Analytics
function gaGet(tableId, startDate, endDate, metrics, options) {
// Apply standard options
options = options || {};
options['max-results'] = options['max-results'] || '10000';
// If errors persist up to 5 times then terminate the program.
for (var i = 0; i < 5; i++) {
try {
return Analytics.Data.Ga.get(tableId, startDate, endDate, metrics, options); // 503
} catch (err) {
// https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors
if (err.message.indexOf('a server error occurred') > -1) {
Logger.log('Backend Error');
// Note: Don't listen to Google's reply and retry request after 2 minutes
Utilities.sleep(2 * 60 * 1000);
} else if (err.message.indexOf('User Rate') > -1) {
Logger.log('Rate Limit Error');
// Exponential Backoff
Utilities.sleep(1000 * Math.pow((i + 1), 2));
} else if (err.message.indexOf('too many concurrent connections') > -1) {
Logger.log('Concurrent Connections Error');
// Exponential Backoff
Utilities.sleep(1000 * Math.pow((i + 1), 2));
} else {
Logger.log(err);
throw err;
}
}
}
throw 'Error. Max retries reached';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment