Skip to content
This repository has been archived by the owner on Jan 30, 2023. It is now read-only.

Commit

Permalink
Always return status as a string in payload errors
Browse files Browse the repository at this point in the history
  • Loading branch information
jaswilli committed Apr 5, 2016
1 parent ec3d68d commit 90bda91
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 2 deletions.
14 changes: 13 additions & 1 deletion addon/ajax-request.js
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,19 @@ export default class AjaxRequest {
*/
normalizeErrorResponse(status, headers, payload) {
if (payload && typeof payload === 'object' && payload.errors) {
return payload.errors;
if (!Ember.isArray(payload.errors)) {
return payload.errors;
}

return payload.errors.map(function(error) {
let ret = merge({}, error);

if (typeof ret.status === 'number') {
ret.status = `${ret.status}`;
}

return ret;
});
} else {
return [
{
Expand Down
3 changes: 2 additions & 1 deletion addon/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -227,5 +227,6 @@ export function isServerError(error) {
* @return {Boolean}
*/
export function isSuccess(status) {
return status >= 200 && status < 300 || status === 304;
let s = parseInt(status, 10);
return s >= 200 && s < 300 || s === 304;
}
38 changes: 38 additions & 0 deletions tests/unit/ajax-request-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -520,6 +520,44 @@ test('it creates a detailed error message for unmatched server errors with a tex
});
});

test('it always returns error objects with status codes as strings', function(assert) {
assert.expect(1);

const response = [404, { 'Content-Type': 'application/json' }, ''];
server.get('/posts', () => response);

const service = new AjaxRequest();
return service.request('/posts')
.then(function() {
assert.ok(false, 'success handler should not be called');
})
.catch(function(result) {
assert.strictEqual(result.errors[0].status, '404', 'status must be a string');
});
});

test('it coerces payload error response status codes to strings', function(assert) {
assert.expect(2);

const body = {
errors: [
{ status: 403, message: 'Permission Denied' }
]
};
const response = [403, { 'Content-Type': 'application/json' }, JSON.stringify(body)];
server.get('/posts', () => response);

const service = new AjaxRequest();
return service.request('/posts')
.then(function() {
assert.ok(false, 'success handler should not be called');
})
.catch(function(result) {
assert.strictEqual(result.errors[0].status, '403', 'status must be a string');
assert.strictEqual(result.errors[0].message, 'Permission Denied');
});
});

test('it throws an error when the user tries to use `.get` to make a request', function(assert) {
assert.expect(3);

Expand Down

0 comments on commit 90bda91

Please sign in to comment.