From cc7cd010055b6af71b48529a6067fda1d0ee16f1 Mon Sep 17 00:00:00 2001 From: Stephen Sawchuk Date: Fri, 30 Oct 2015 13:58:41 -0400 Subject: [PATCH] core: use error message from response body --- lib/common/util.js | 10 ++++++++- test/common/util.js | 53 ++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 59 insertions(+), 4 deletions(-) diff --git a/lib/common/util.js b/lib/common/util.js index f4b5775b631..ca86014e65a 100644 --- a/lib/common/util.js +++ b/lib/common/util.js @@ -115,8 +115,16 @@ util.noop = noop; var ApiError = createErrorClass('ApiError', function(errorBody) { this.errors = errorBody.errors; this.code = errorBody.code; - this.message = errorBody.message || 'Error during request.'; + this.message = errorBody.message; this.response = errorBody.response; + + if (!this.message) { + if (errorBody.errors && errorBody.errors.length === 1) { + this.message = errorBody.errors[0].message; + } else { + this.message = 'Error during request.'; + } + } }); /** diff --git a/test/common/util.js b/test/common/util.js index 5b630842416..fcb507076a2 100644 --- a/test/common/util.js +++ b/test/common/util.js @@ -127,16 +127,63 @@ describe('common/util', function() { assert.strictEqual(apiError.response, error.response); }); - it('should build ApiError with default status message', function() { + it('should detect ApiError message from response body', function() { + var errorMessage = 'API error message'; + var error = { - errors: [], + errors: [ new Error(errorMessage) ], code: 100, response: { a: 'b', c: 'd' } }; var apiError = new util.ApiError(error); - assert.strictEqual(apiError.message, 'Error during request.'); + assert.strictEqual(apiError.message, errorMessage); + }); + + it('should favor an explicit message over response body', function() { + var errorMessage = 'API error message'; + var expectedErrorMessage = 'Custom error message'; + + var error = { + errors: [ new Error(errorMessage) ], + code: 100, + response: { a: 'b', c: 'd' }, + message: expectedErrorMessage + }; + + var apiError = new util.ApiError(error); + + assert.strictEqual(apiError.message, expectedErrorMessage); + }); + + it('should use default message if there are no errors', function() { + var expectedErrorMessage = 'Error during request.'; + + var error = { + code: 100, + response: { a: 'b', c: 'd' }, + message: expectedErrorMessage + }; + + var apiError = new util.ApiError(error); + + assert.strictEqual(apiError.message, expectedErrorMessage); + }); + + it('should use default message if too many errors', function() { + var expectedErrorMessage = 'Error during request.'; + + var error = { + errors: [ new Error(), new Error() ], + code: 100, + response: { a: 'b', c: 'd' }, + message: expectedErrorMessage + }; + + var apiError = new util.ApiError(error); + + assert.strictEqual(apiError.message, expectedErrorMessage); }); });