Useless middleware for testing purposes:
module.exports = function () {
return function rankick(req, res, next) {
if (Math.random() < 0.5) {
return next('Random kick...');
}
next();
};
};
Injected into a simple express app:
var express = require('express'),
http = require('http'),
path = require('path')
rankick= require('./rankick'),
util = require('util');
var app = express();
app.set('port', process.env.PORT || 8080);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));
app.use(rankick()); // Using the middleware
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.use(function (req, res, next) {
res.end('Hello World!');
});
http.createServer(app).listen(app.get('port'));
When next() is invoked with the error string, console logs undefined followed by the 500 error:
undefined
GET / 500 28ms
GET / 200 4ms
undefined
GET / 500 5ms
Is it's this line in the errorHandler middleware. Maybe it expects to get a new Error('Random kick..')?
It's been a while since I used to default errorHandler so I am not 100% sure. In case it's not downvote and I'll remove this answer.
You should do
module.exports = function rankick(req, res, next) {
if (Math.random() < 0.5) {
console.log('Random kick...');
}
else
next();
};
Don't use return to pass the function. module.exports is the object that is passed when require is called.
Also next() is supposed to be called if you want to continue processing to next middleware. If you want to stop processing/kick request don't call next()