Permalink
Browse files

Added double-next reporting

  • Loading branch information...
1 parent fda5b8d commit 4046ad095fb0a871e010e7d9f92f428db3c17fdf @tj tj committed Aug 26, 2011
Showing with 36 additions and 3 deletions.
  1. +36 −3 lib/http.js
View
@@ -133,6 +133,7 @@ Server.prototype.use = function(route, handle){
Server.prototype.handle = function(req, res, out) {
var writeHead = res.writeHead
, stack = this.stack
+ , called = []
, removed = ''
, index = 0;
@@ -144,6 +145,17 @@ Server.prototype.handle = function(req, res, out) {
layer = stack[index++];
+ // callback used to track
+ // and report double next()
+ function callback(err) {
+ if (~called.indexOf(layer.handle)) {
+ reportDoubleNext(layer.handle);
+ } else {
+ called.push(layer.handle);
+ next(err);
+ }
+ }
+
// all done
if (!layer) {
// but wait! we have a parent
@@ -190,12 +202,12 @@ Server.prototype.handle = function(req, res, out) {
var arity = layer.handle.length;
if (err) {
if (arity === 4) {
- layer.handle(err, req, res, next);
+ layer.handle(err, req, res, callback);
} else {
next(err);
}
} else if (arity < 4) {
- layer.handle(req, res, next);
+ layer.handle(req, res, callback);
} else {
next();
}
@@ -209,4 +221,25 @@ Server.prototype.handle = function(req, res, out) {
}
}
next();
-};
+};
+
+/**
+ * Report that the given `fn` was invoked
+ * more than once. This _is_ an error, and
+ * should be fixed in your application, however
+ * this logic prevents the user from seeing
+ * how node handles it via more obscure
+ * errors such as: "Error: Can't set headers after they are sent."
+ *
+ * @param {Function} fn
+ * @api private
+ */
+
+function reportDoubleNext(fn) {
+ process.stderr.write('Error: the following middleware invoked next() more than once: ');
+ if (fn.name) {
+ console.error(fn.name + '()');
+ } else {
+ console.error('\n\n' + fn.toString() + '\n');
+ }
+}

0 comments on commit 4046ad0

Please sign in to comment.