From 900294a13d9c7b184eb3da332b4eba7c06602ad0 Mon Sep 17 00:00:00 2001 From: Felix Hammerl Date: Tue, 27 Jan 2015 12:24:13 +0100 Subject: [PATCH] [WO-857] improved error reporting after XHR --- src/js/service/admin.js | 4 ++-- src/js/service/rest.js | 40 +++++++++++++++++++--------------------- 2 files changed, 21 insertions(+), 23 deletions(-) diff --git a/src/js/service/admin.js b/src/js/service/admin.js index a36bdfa..71b8bc4 100644 --- a/src/js/service/admin.js +++ b/src/js/service/admin.js @@ -30,7 +30,7 @@ Admin.prototype.createUser = function(options) { throw new Error('User name is already taken!'); } - throw new Error('Error creating new user!'); + throw new Error('Error creating new user! Reason: ' + err.message); }); }; @@ -57,6 +57,6 @@ Admin.prototype.validateUser = function(options) { return; } - throw new Error('Validation failed!'); + throw new Error('Validation failed! Reason: ' + err.message); }); }; \ No newline at end of file diff --git a/src/js/service/rest.js b/src/js/service/rest.js index 2449f8d..f2cfce5 100644 --- a/src/js/service/rest.js +++ b/src/js/service/rest.js @@ -101,10 +101,7 @@ RestDAO.prototype._processRequest = function(options) { var xhr, format; if (typeof options.uri === 'undefined') { - throw { - code: 400, - message: 'Bad Request! URI is a mandatory parameter.' - }; + throw createError(400, 'Bad Request! URI is a mandatory parameter.'); } options.type = options.type || 'json'; @@ -116,10 +113,7 @@ RestDAO.prototype._processRequest = function(options) { } else if (options.type === 'text') { format = 'text/plain'; } else { - throw { - code: 400, - message: 'Bad Request! Unhandled data type.' - }; + throw createError(400, 'Bad Request! Unhandled data type.'); } xhr = new XMLHttpRequest(); @@ -130,30 +124,34 @@ RestDAO.prototype._processRequest = function(options) { xhr.onload = function() { var res; - if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 201 || xhr.status === 304)) { - if (options.type === 'json') { - res = xhr.responseText ? JSON.parse(xhr.responseText) : xhr.responseText; - } else { + if (options.type === 'json') { + try { + res = JSON.parse(xhr.responseText); + } catch(e) { res = xhr.responseText; } + } else { + res = xhr.responseText; + } + if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 201 || xhr.status === 304)) { resolve(res); return; } - reject({ - code: xhr.status, - message: xhr.statusText - }); + reject(createError(xhr.status, (res && res.error) || xhr.statusText)); }; xhr.onerror = function() { - reject({ - code: 42, - message: 'Error calling ' + options.method + ' on ' + options.uri - }); + reject(createError(42, 'Error calling ' + options.method + ' on ' + options.uri)); }; xhr.send(options.payload ? JSON.stringify(options.payload) : undefined); }); -}; \ No newline at end of file +}; + +function createError(code, message) { + var error = new Error(message); + error.code = code; + return error; +} \ No newline at end of file