From ad0dd3cc39c27d71149dcaa8f7f7807cd7e3ed8e Mon Sep 17 00:00:00 2001 From: TJ Holowaychuk Date: Tue, 27 Aug 2013 20:54:13 -0700 Subject: [PATCH] add Context#error(). Closes #31 --- lib/context.js | 25 +++++++++++++++++++++++++ test/context.js | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) diff --git a/lib/context.js b/lib/context.js index 33d60af..5cb1cf3 100644 --- a/lib/context.js +++ b/lib/context.js @@ -554,6 +554,31 @@ module.exports = { return this.res.headersSent; }, + /** + * Throw an error with `msg` and optional `status` + * defaulting to 500. + * + * this.error(403) + * this.error('name required', 400) + * this.error('something exploded') + * + * @param {String|Number} msg + * @param {Number} status + * @api public + */ + + error: function(msg, status){ + if ('number' == typeof msg) { + var tmp = msg; + msg = http.STATUS_CODES[tmp]; + status = tmp; + } + + var err = new Error(msg); + err.status = status || 500; + throw err; + }, + /** * Default error handling. * diff --git a/test/context.js b/test/context.js index b332024..ea364c5 100644 --- a/test/context.js +++ b/test/context.js @@ -21,6 +21,47 @@ function context(req, res) { return ctx; } +describe('ctx.error(msg)', function(){ + it('should set .status to 500', function(done){ + var ctx = context(); + + try { + ctx.error('boom'); + } catch (err) { + assert(500 == err.status); + done(); + } + }) +}) + +describe('ctx.error(msg, status)', function(){ + it('should throw an error', function(done){ + var ctx = context(); + + try { + ctx.error('name required', 400); + } catch (err) { + assert('name required' == err.message); + assert(400 == err.status); + done(); + } + }) +}) + +describe('ctx.error(status)', function(){ + it('should throw an error', function(done){ + var ctx = context(); + + try { + ctx.error(400); + } catch (err) { + assert('Bad Request' == err.message); + assert(400 == err.status); + done(); + } + }) +}) + describe('ctx.length', function(){ describe('when Content-Length is defined', function(){ it('should return a number', function(){