context.throw supports Error instances

This commit is contained in:
Veselin Todorov 2014-01-04 10:23:39 +02:00
parent e8c0e19b92
commit 6cd4c776f8
2 changed files with 51 additions and 4 deletions

View file

@ -54,9 +54,11 @@ module.exports = {
* this.throw('name required', 400) * this.throw('name required', 400)
* this.throw(400, 'name required') * this.throw(400, 'name required')
* this.throw('something exploded') * 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|Error} err, msg or status
* @param {String|Number} msg or status * @param {String|Number|Error} err, msg or status
* @api public * @api public
*/ */
@ -67,7 +69,7 @@ module.exports = {
status = tmp; status = tmp;
} }
var err = new Error(msg); var err = msg instanceof Error ? msg : new Error(msg);
err.status = status || 500; err.status = status || 500;
err.expose = true; err.expose = true;
throw err; throw err;

View file

@ -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(){ describe('ctx.throw(msg, status)', function(){
it('should throw an error', function(done){ it('should throw an error', function(done){
var ctx = context(); var ctx = context();
@ -55,4 +100,4 @@ describe('ctx.throw(status)', function(){
done(); done();
} }
}) })
}) })