[WO-857] improved error reporting after XHR

This commit is contained in:
Felix Hammerl 2015-01-27 12:24:13 +01:00
parent 990950bc48
commit 900294a13d
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('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; 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; var xhr, format;
if (typeof options.uri === 'undefined') { if (typeof options.uri === 'undefined') {
throw { throw createError(400, 'Bad Request! URI is a mandatory parameter.');
code: 400,
message: 'Bad Request! URI is a mandatory parameter.'
};
} }
options.type = options.type || 'json'; options.type = options.type || 'json';
@ -116,10 +113,7 @@ RestDAO.prototype._processRequest = function(options) {
} else if (options.type === 'text') { } else if (options.type === 'text') {
format = 'text/plain'; format = 'text/plain';
} else { } else {
throw { throw createError(400, 'Bad Request! Unhandled data type.');
code: 400,
message: 'Bad Request! Unhandled data type.'
};
} }
xhr = new XMLHttpRequest(); xhr = new XMLHttpRequest();
@ -130,30 +124,34 @@ RestDAO.prototype._processRequest = function(options) {
xhr.onload = function() { xhr.onload = function() {
var res; var res;
if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 201 || xhr.status === 304)) { if (options.type === 'json') {
if (options.type === 'json') { try {
res = xhr.responseText ? JSON.parse(xhr.responseText) : xhr.responseText; res = JSON.parse(xhr.responseText);
} else { } catch(e) {
res = xhr.responseText; res = xhr.responseText;
} }
} else {
res = xhr.responseText;
}
if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 201 || xhr.status === 304)) {
resolve(res); resolve(res);
return; return;
} }
reject({ reject(createError(xhr.status, (res && res.error) || xhr.statusText));
code: xhr.status,
message: xhr.statusText
});
}; };
xhr.onerror = function() { xhr.onerror = function() {
reject({ reject(createError(42, 'Error calling ' + options.method + ' on ' + options.uri));
code: 42,
message: 'Error calling ' + options.method + ' on ' + options.uri
});
}; };
xhr.send(options.payload ? JSON.stringify(options.payload) : undefined); xhr.send(options.payload ? JSON.stringify(options.payload) : undefined);
}); });
}; };
function createError(code, message) {
var error = new Error(message);
error.code = code;
return error;
}