add Context#error(). Closes #31

This commit is contained in:
TJ Holowaychuk 2013-08-27 20:54:13 -07:00
parent f6a2f54aef
commit ad0dd3cc39
2 changed files with 66 additions and 0 deletions

View File

@ -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.
*

View File

@ -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(){