From cda9636e8f427b62d9addd38cafadac105cd3456 Mon Sep 17 00:00:00 2001 From: Tony Apuzzo Date: Tue, 8 Mar 2016 18:15:49 -0700 Subject: [PATCH] Fix incorrect handling of Error objects in handleError() and add test to prevent regression of same. With this change the error response created by the default response hooks will include more information when an error is encountered while processing a request. The body of the HTTP response will include a message and stack (if not in production.) --- lib/hooks/responses/index.js | 5 ++--- test/unit/req.errors.test.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/lib/hooks/responses/index.js b/lib/hooks/responses/index.js index 862654924..33936d1f2 100644 --- a/lib/hooks/responses/index.js +++ b/lib/hooks/responses/index.js @@ -183,12 +183,11 @@ function _mixin_jsonx(req, res) { if (!jsonSerializedErr.stack || !jsonSerializedErr.message) { jsonSerializedErr.message = err.message; jsonSerializedErr.stack = err.stack; - - return jsonSerializedErr; } + return jsonSerializedErr; } catch (e){ - return {message: err.message, stack: err.stack}; + return {name: err.name, message: err.message, stack: err.stack}; } } diff --git a/test/unit/req.errors.test.js b/test/unit/req.errors.test.js index aa7dac755..1b34e5627 100644 --- a/test/unit/req.errors.test.js +++ b/test/unit/req.errors.test.js @@ -18,6 +18,15 @@ describe('request that causes an error', function (){ 'responses' ] }); + var saveServerError; + + // Restore the default error handler after tests that change it + afterEach(function () { + if (saveServerError) { + sails.registry.responses.serverError = saveServerError; + saveServerError = undefined; + } + }); it('should return the expected error when something throws', function (done) { @@ -40,6 +49,7 @@ describe('request that causes an error', function (){ var ERROR = 'oh no I forgot my keys'; var CHECKPOINT = 'made it'; + saveServerError = sails.registry.responses.serverError; sails.registry.responses.serverError = function (err) { assert.deepEqual(ERROR, err); this.res.send(500, CHECKPOINT); @@ -56,4 +66,22 @@ describe('request that causes an error', function (){ }); + it('should return the expected error when something throws an Error object', function (done) { + + var MESSAGE = 'oh no I forgot my keys again'; + var ERROR = new Error(MESSAGE); + + sails.get('/errors/3', function (req, res) { + throw ERROR; + }); + + sails.request('GET /errors/3', {}, function (err) { + assert.deepEqual(err.status, 500); + assert.deepEqual(typeof(err.body), 'object'); + assert.deepEqual(err.body.message, MESSAGE); + done(); + }); + + }); + });