Merge pull request #334 from ianstormtaylor/add/throw-optional-status

Add/throw optional status
This commit is contained in:
TJ Holowaychuk 2014-08-12 14:23:03 -07:00
commit 27356125eb
3 changed files with 59 additions and 8 deletions

View file

@ -102,10 +102,11 @@ throw err;
error messages since you do not want to leak failure
details.
You may optionall pass a `properties` object which is merged into the error as-is, useful for decorating machine-friendly errors which are reported to the requester upstream.
You may optionally pass a `properties` object which is merged into the error as-is, useful for decorating machine-friendly errors which are reported to the requester upstream.
```js
this.throw(401, 'access_denied', { user: user });
this.throw('access_denied', { user: user });
```
### ctx.respond

View file

@ -62,27 +62,29 @@ var proto = module.exports = {
* this.throw(400, new Error('invalid'));
*
* @param {String|Number|Error} err, msg or status
* @param {String|Number|Error} err, msg or status
* @param {String|Number|Error} [err, msg or status]
* @param {Object} [props]
* @api public
*/
throw: function(msg, status, props){
if ('object' == typeof status && !(status instanceof Error)) {
props = status;
status = null;
}
if ('number' == typeof msg) {
var tmp = msg;
msg = status || http.STATUS_CODES[tmp];
status = tmp;
}
props = props || {};
var err = msg instanceof Error ? msg : new Error(msg);
if (props) {
for (var key in props) err[key] = props[key];
}
err.status = status || err.status || 500;
err.expose = 'number' == typeof err.status && http.STATUS_CODES[err.status] && err.status < 500;
throw err;
},

View file

@ -159,3 +159,51 @@ describe('ctx.throw(status, msg, props)', function(){
})
})
})
describe('ctx.throw(msg, props)', function(){
it('should mixin props', function(done){
var ctx = context();
try {
ctx.throw('msg', { prop: true });
} catch (err) {
assert('msg' == err.message);
assert(500 == err.status);
assert(false === err.expose);
assert(true === err.prop);
done();
}
})
})
describe('ctx.throw(status, props)', function(){
it('should mixin props', function(done){
var ctx = context();
try {
ctx.throw(400, { prop: true });
} catch (err) {
assert('Bad Request' == err.message);
assert(400 == err.status);
assert(true === err.expose);
assert(true === err.prop);
done();
}
})
})
describe('ctx.throw(err, props)', function(){
it('should mixin props', function(done){
var ctx = context();
try {
ctx.throw(new Error('test'), { prop: true });
} catch (err) {
assert('test' == err.message);
assert(500 == err.status);
assert(false === err.expose);
assert(true === err.prop);
done();
}
})
})