diff --git a/lib/response.js b/lib/response.js index 6ab51223310..244586e010e 100644 --- a/lib/response.js +++ b/lib/response.js @@ -56,8 +56,13 @@ var charsetRegExp = /;\s*charset\s*=/; * @public */ -res.status = function status(code) { - this.statusCode = code; +res.status = function status(statusCode) { + // check that status code is valid + if (typeof statusCode !== 'number' || statusCode < 100 || statusCode > 999) { + throw new TypeError('Invalid status code.'); + } + + this.statusCode = statusCode; return this; }; @@ -110,7 +115,7 @@ res.send = function send(body) { // support res.send(status, body) if (arguments.length === 2) { deprecate('res.send(status, body): Use res.status(status).send(body) instead'); - this.statusCode = arguments[0]; + this.status(arguments[0]); chunk = arguments[1]; } @@ -169,7 +174,7 @@ res.send = function send(body) { } // freshness - if (req.fresh) this.statusCode = 304; + if (req.fresh) this.status(304); // strip irrelevant headers if (204 === this.statusCode || 304 === this.statusCode) { @@ -208,7 +213,7 @@ res.json = function json(obj) { // support res.json(status, obj) if (arguments.length === 2) { deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[0]; + this.status(arguments[0]); val = arguments[1]; } @@ -244,7 +249,7 @@ res.jsonp = function jsonp(obj) { // support res.jsonp(status, obj) if (arguments.length === 2) { deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); - this.statusCode = arguments[0]; + this.status(arguments[0]); val = arguments[1]; } @@ -304,11 +309,10 @@ res.jsonp = function jsonp(obj) { */ res.sendStatus = function sendStatus(statusCode) { - var body = statusCodes[statusCode] || String(statusCode); - - this.statusCode = statusCode; + this.status(statusCode); this.type('txt'); + var body = statusCodes[statusCode] || String(statusCode); return this.send(body); }; @@ -788,7 +792,7 @@ res.redirect = function redirect(url) { }); // Respond - this.statusCode = status; + this.status(status); this.set('Content-Length', Buffer.byteLength(body)); if (this.req.method === 'HEAD') { diff --git a/test/res.status.js b/test/res.status.js index 8c173a645c5..215092724c5 100644 --- a/test/res.status.js +++ b/test/res.status.js @@ -16,5 +16,29 @@ describe('res', function(){ .expect('Created') .expect(201, done); }) + + it('should throw a TypeError if not a number', function(done) { + var app = express(); + + app.use(function(req, res){ + res.status('foo').end(); + }); + + request(app) + .get('/') + .expect(500, /Invalid status code/, done); + }) + + it('should throw a TypeError if invalid number', function(done){ + var app = express(); + + app.use(function(req, res){ + res.status(10000).end(); + }); + + request(app) + .get('/') + .expect(500, /Invalid status code/, done); + }) }) })