Skip to content
This repository has been archived by the owner on Sep 8, 2020. It is now read-only.

Commit

Permalink
Merge pull request #54 from nareddyt/get-request-timeout
Browse files Browse the repository at this point in the history
Add timeouts to HTTP Requests + better error handling
  • Loading branch information
nareddyt authored Apr 5, 2018
2 parents d213368 + ecbb014 commit 9d1a922
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions src/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const CASHBACK_DATA_PATH_DEV = '../data/cashback/data.json';
const DEAL_DATA_PATH_DEV = '../data/deal/data.json';
const REFRESH_DATA_ALARM_NAME = 'refresh-data-alarm';
const REFRESH_DATA_INTERVAL_MINUTES = 60;
const REQUEST_TIMEOUT_SECONDS = 10;

// Loaded data from the url / files (depending on mode)
let cashbacks = null;
Expand Down Expand Up @@ -232,18 +233,31 @@ function fetchJSON(location, callback) {
let httpRequest = new XMLHttpRequest();

httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.readyState === XMLHttpRequest.DONE) {

if (httpRequest.status === 200) {
let data = JSON.parse(httpRequest.responseText);
return callback(null, data);

try {
let data = JSON.parse(httpRequest.responseText);
return callback(null, data);
} catch (e) {
return callback(e, null);
}

} else {
let err = 'Failed loading data from: ' + location;
let err = 'HTTP Error Code: ' + httpRequest.status;
return callback(err, null);
}
}
};

httpRequest.ontimeout = function (e) {
let err = 'Request timed out after ' + REQUEST_TIMEOUT_SECONDS + ' seconds';
callback(err, null);
};

httpRequest.open('GET', location);
httpRequest.timeout = REQUEST_TIMEOUT_SECONDS * 1000;
httpRequest.send();
}

Expand Down

0 comments on commit 9d1a922

Please sign in to comment.