diff --git a/lib/index.js b/lib/index.js index dd1cf41..d57c2f0 100755 --- a/lib/index.js +++ b/lib/index.js @@ -85,6 +85,13 @@ exports.create = function (statusCode, message, data) { internals.create = function (statusCode, message, data, ctor) { + if (message instanceof Error) { + if (data) { + message.data = data; + } + return exports.wrap(message, statusCode); + } + const error = new Error(message ? message : undefined); // Avoids settings null message Error.captureStackTrace(error, ctor); // Filter the stack to our external API error.data = data || null; diff --git a/test/index.js b/test/index.js index 53b89d6..0ca8e84 100755 --- a/test/index.js +++ b/test/index.js @@ -726,3 +726,43 @@ describe('stack trace', () => { done(); }); }); + +describe('method with error object instead of message', () => { + + ['badRequest', 'unauthorized', 'forbidden', 'notFound', 'methodNotAllowed', + 'notAcceptable', 'proxyAuthRequired', 'clientTimeout', 'conflict', + 'resourceGone', 'lengthRequired', 'preconditionFailed', 'entityTooLarge', + 'uriTooLong', 'unsupportedMediaType', 'rangeNotSatisfiable', 'expectationFailed', + 'badData', 'preconditionRequired', 'tooManyRequests', + + // 500s + 'internal', 'notImplemented', 'badGateway', 'serverUnavailable', + 'gatewayTimeout', 'badImplementation' + ].forEach((name) => { + + it(`should allow \`Boom${name}(err)\` and preserve the error`, (done) => { + + const error = new Error('An example mongoose validation error'); + error.name = 'ValidationError'; + const err = Boom[name](error); + expect(err.name).to.equal('ValidationError'); + expect(err.message).to.equal('An example mongoose validation error'); + done(); + }); + + // exclude unauthorized + if (name !== 'unauthorized') { + + it(`should allow \`Boom.${name}(err, data)\` and preserve the data`, (done) => { + + const error = new Error(); + const err = Boom[name](error, { foo: 'bar' }); + expect(err.data).to.equal({ foo: 'bar' }); + done(); + }); + + } + + }); + +});