diff --git a/lib/application.js b/lib/application.js index 5f8744c..601728a 100644 --- a/lib/application.js +++ b/lib/application.js @@ -152,7 +152,7 @@ function *respond(next){ if (false === this.respond) return; var res = this.res; - if (res.headersSent || !res.socket.writable) return; + if (res.headersSent || !this.writable) return; var body = this.body; var status = this.status = this.status || 404; diff --git a/lib/context.js b/lib/context.js index c339774..a0a9cb7 100644 --- a/lib/context.js +++ b/lib/context.js @@ -106,7 +106,7 @@ var proto = module.exports = { // nothing we can do here other // than delegate to the app-level // handler and log. - if (this.headerSent || !this.socket.writable) { + if (this.headerSent || !this.writable) { err.headerSent = true; this.app.emit('error', err, this); return; @@ -153,6 +153,7 @@ delegate(proto, 'response') .access('type') .access('charset') .getter('headerSent') + .getter('writable') .setter('lastModified') .setter('etag'); diff --git a/lib/response.js b/lib/response.js index bae33d3..2c75efc 100644 --- a/lib/response.js +++ b/lib/response.js @@ -434,6 +434,21 @@ module.exports = { this.set(field, list.join(', ')); }, + /** + * Checks if the request is writable. + * Tests for the existence of the socket + * as node sometimes does not set it. + * + * @return {Boolean} + * @api private + */ + + get writable() { + var socket = this.res.socket; + if (!socket) return false; + return socket.writable; + }, + /** * Inspect implementation. * diff --git a/test/context/writable.js b/test/context/writable.js new file mode 100644 index 0000000..fd18ee0 --- /dev/null +++ b/test/context/writable.js @@ -0,0 +1,10 @@ + +var context = require('../context'); + +describe('ctx.writable', function(){ + it('should not crash when the socket does not exist', function(){ + var ctx = context(); + ctx.socket = null; + ctx.writable.should.equal(false); + }) +}) \ No newline at end of file