The official Node docs say we should shutdown the process after receiving an error with domains:
var server = require('http').createServer(function(req, res) {
var d = domain.create();
d.on('error', function(er) {
console.error('error', er.stack);
// Note: we're in dangerous territory!
// By definition, something unexpected occurred,
// which we probably didn't want.
// Anything can happen now! Be very careful!
try {
// make sure we close down within 30 seconds
var killtimer = setTimeout(function() {
process.exit(1);
}, 30000);
// But don't keep the process open just for that!
killtimer.unref();
// stop taking new requests.
server.close();
// Let the master know we're dead. This will trigger a
// 'disconnect' in the cluster master, and then it will fork
// a new worker.
cluster.worker.disconnect();
// try to send an error to the request that triggered the problem
res.statusCode = 500;
res.setHeader('content-type', 'text/plain');
res.end('Oops, there was a problem!\n');
} catch (er2) {
// oh well, not much we can do at this point.
console.error('Error sending 500!', er2.stack);
}
});
// Because req and res were created before this domain existed,
// we need to explicitly add them.
// See the explanation of implicit vs explicit binding below.
d.add(req);
d.add(res);
// Now run the handler function in the domain.
d.run(function() {
handleRequest(req, res);
});
});
server.listen(PORT);
}
How can this be adapted to connect-domain? I have some simple skeleton code I started with, but it is missing some critical pieces that I don't understand:
var express = require('express');
var app = express();
var connectDomain = require('connect-domain');
app.use(express.static('/public'));
app.use(connectDomain());
app.get('/', function(req, res) {
res.send('Hello World!');
});
// This is where I would handle process shutdown
app.use(function(err, req, res, next) {
try {
// Adapting nodejs process shutdown here
var killtimer = setTimeout(function() {
process.exit(1);
}, 30000);
// But don't keep the process open just for that!
killtimer.unref();
// ??? How to close server ???
// server.close();
// try to send an error to the request that triggered the problem
res.statusCode = 500;
res.setHeader('content-type', 'text/plain');
res.end('Oops, there was a problem!\n');
} catch (er2) {
console.log('Error sending 500!, er2.stack);
}
});
// ??? How would the following be adapted ???
/*----------------
d.add(req);
d.add(res);
// Now run the handler function in the domain.
d.run(function() {
handleRequest(req, res);
});
---------------*/
// Start application
app.listen(3000, function() {
console.log("Express app started!");
});
The official Node docs say we should shutdown the process after receiving an error with
domains
:How can this be adapted to
connect-domain
? I have some simple skeleton code I started with, but it is missing some critical pieces that I don't understand: