From 6cd4c776f8174ad9de4e8cdcc3fb3017be31f8fa Mon Sep 17 00:00:00 2001 From: Veselin Todorov Date: Sat, 4 Jan 2014 10:23:39 +0200 Subject: [PATCH] context.throw supports Error instances --- lib/context.js | 8 +++++--- test/context/throw.js | 47 ++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/lib/context.js b/lib/context.js index 111a107..7a4fd6a 100644 --- a/lib/context.js +++ b/lib/context.js @@ -54,9 +54,11 @@ module.exports = { * this.throw('name required', 400) * this.throw(400, 'name required') * this.throw('something exploded') + * this.throw(new Error('invalid'), 400); + * this.throw(400, new Error('invalid')); * - * @param {String|Number} msg or status - * @param {String|Number} msg or status + * @param {String|Number|Error} err, msg or status + * @param {String|Number|Error} err, msg or status * @api public */ @@ -67,7 +69,7 @@ module.exports = { status = tmp; } - var err = new Error(msg); + var err = msg instanceof Error ? msg : new Error(msg); err.status = status || 500; err.expose = true; throw err; diff --git a/test/context/throw.js b/test/context/throw.js index d3b25a2..184d5da 100644 --- a/test/context/throw.js +++ b/test/context/throw.js @@ -15,6 +15,51 @@ describe('ctx.throw(msg)', function(){ }) }) +describe('ctx.throw(err)', function(){ + it('should set .status to 500', function(done){ + var ctx = context(); + var err = new Error('test'); + + try { + ctx.throw(err); + } catch (err) { + assert(500 == err.status); + assert('test' == err.message); + done(); + } + }) +}) + +describe('ctx.throw(err, status)', function(){ + it('should throw the error and set .status', function(done){ + var ctx = context(); + var error = new Error('test'); + + try { + ctx.throw(error, 422); + } catch (err) { + assert(422 == err.status); + assert('test' == err.message); + done(); + } + }) +}) + +describe('ctx.throw(status, err)', function(){ + it('should throw the error and set .status', function(done){ + var ctx = context(); + var error = new Error('test'); + + try { + ctx.throw(422, error); + } catch (err) { + assert(422 == err.status); + assert('test' == err.message); + done(); + } + }) +}) + describe('ctx.throw(msg, status)', function(){ it('should throw an error', function(done){ var ctx = context(); @@ -55,4 +100,4 @@ describe('ctx.throw(status)', function(){ done(); } }) -}) \ No newline at end of file +})