diff --git a/addon/ajax-request.js b/addon/ajax-request.js index f790e180..c89aa23a 100644 --- a/addon/ajax-request.js +++ b/addon/ajax-request.js @@ -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 [ { diff --git a/addon/errors.js b/addon/errors.js index 7650fa35..3efe73ef 100644 --- a/addon/errors.js +++ b/addon/errors.js @@ -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; } diff --git a/tests/unit/ajax-request-test.js b/tests/unit/ajax-request-test.js index b04565b0..a1978be3 100644 --- a/tests/unit/ajax-request-test.js +++ b/tests/unit/ajax-request-test.js @@ -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);