var domainMiddleware = require('express-domain-middleware');
domainMiddleware = function(req, res, next)
Exports a function matching the signature of express middleware. Binds incoming request & response from express to a new domain. Assigns the domain a unique id by calling domainMiddleware.id(req).
If the domain emits an error event, domainMiddleware will call next(err) with the error event from the domain. This allows existing express specific error handling middleware to
function as if the error was hanlded by your application code. Allow me to demonstrate with an example:
///old-school
app.get('/error',function(req,res,next){
db.query('SELECT happiness()',function(err,rows){
if(err)returnnext(err);
fs.readFile('alskdjflasd',function(err,contents){
if(err)returnnext(err);
process.nextTick(function(){
thrownewError("congratulations, your node process crashed and the user request disconnected in a jarring way");
});
});
})
});
now with less crashing...
//with domain-middleware
app.use(require('express-domain-middleware'));
app.use(app.router);
app.use(functionerrorHandler(err,req,res,next){
console.log('error on request %d %s %s: %j',process.domain.id,req.method,req.url, err);
res.send(500,"Something bad happened. :(");
if(err.domain){
//you should think about gracefully stopping & respawning your server
//since an unhandled error might put your application into an unknown state