Skip to content

Commit dc1b23c

Browse files
illyaVvengrov
authored andcommitted
Add HTTP request error handling (#64)
1 parent 1515106 commit dc1b23c

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

examples/file-service/js/files-example.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,8 @@
9898

9999
function getItemsFromPersistance() {
100100
return Backendless.Persistence.of(FileItem).find().catch(function (e) {
101-
alert(e.code == 1009 ? 'Please upload a file first' : e.message);
102-
return [];
101+
alert(e.code == 1009 ? 'Please upload a file first' : e.message || e);
102+
return { data: [] };
103103
});
104104
}
105105

libs/backendless.js

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,20 @@
187187
return ui8a;
188188
};
189189

190+
Utils.onHttpRequestErrorHandler = function (xhr, errorHandler, responseParser) {
191+
return function() {
192+
var errorMessage = 'Unable to connect to the network';
193+
194+
//this part is needed for those implementations of XMLHttpRequest
195+
//which call the onerror handler on an any bad request
196+
if (xhr.status >= 400) {
197+
errorMessage = responseParser(xhr);
198+
}
199+
200+
errorHandler(errorMessage);
201+
};
202+
};
203+
190204
function tryParseJSON(s) {
191205
try {
192206
return typeof s === 'string' ? JSON.parse(s) : s;
@@ -336,7 +350,7 @@
336350

337351
if (config.isAsync) {
338352
xhr.onreadystatechange = function() {
339-
if (xhr.readyState == 4) {
353+
if (xhr.readyState == 4 && xhr.status) {
340354
if (xhr.status >= 200 && xhr.status < 300) {
341355
response = parseResponse(xhr);
342356
cacheHandler(response);
@@ -348,6 +362,10 @@
348362
}
349363
}
350364
};
365+
366+
if (config.asyncHandler.fault) {
367+
xhr.onerror = Utils.onHttpRequestErrorHandler(xhr, config.asyncHandler.fault, badResponse);
368+
}
351369
}
352370

353371
xhr.send(config.data);
@@ -2141,7 +2159,7 @@
21412159
asyncHandler: responder
21422160
});
21432161
},
2144-
2162+
21452163
/** @deprecated */
21462164
addPoint: function(geopoint, async) {
21472165
return this.savePoint.apply(this, arguments);
@@ -3417,14 +3435,16 @@
34173435

34183436
if (async) {
34193437
xhr.onreadystatechange = function() {
3420-
if (xhr.readyState == 4) {
3438+
if (xhr.readyState == 4 && xhr.status) {
34213439
if (xhr.status >= 200 && xhr.status < 300) {
34223440
async.success(JSON.parse(xhr.responseText));
34233441
} else {
34243442
async.fault(JSON.parse(xhr.responseText));
34253443
}
34263444
}
34273445
};
3446+
3447+
xhr.onerror = Utils.onHttpRequestErrorHandler(xhr, async.fault, badResponse);
34283448
}
34293449

34303450
xhr.send(encoded ? options.data : Utils.stringToBiteArray(getBuilder(options.fileName, options.data, boundary)));

0 commit comments

Comments
 (0)