Merge pull request #257 from whiteout-io/dev/WO-857

[WO-857] improved error reporting after XHR
This commit is contained in:
Tankred Hase 2015-02-02 15:43:56 +01:00
commit 86653e8700
2 changed files with 21 additions and 23 deletions

View File

@ -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);
});
};

View File

@ -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;
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);
});
};
function createError(code, message) {
var error = new Error(message);
error.code = code;
return error;
}