Permalink
Browse files

Check app compatiblity before starting server

  • Loading branch information...
1 parent 15c4624 commit 2f4baf9db2fda87c87e312016eece29e49335efe @camshaft committed Jan 8, 2013
Showing with 42 additions and 25 deletions.
  1. +42 −25 lib/runner.js
View
@@ -1,16 +1,44 @@
var domain = require('domain')
- , http = require('http');
+ , http = require('http')
+ , port = process.env.PORT || 3000;
module.exports = function(appPath) {
-
- var app = require(appPath)
- , port = process.env.PORT || 3000
- , serverDomain = domain.create();
+ var serverDomain = domain.create()
+ , server;
// Catch all unhandled exceptions for the server
serverDomain.run(function() {
- var server = http.createServer(function(req, res) {
+ var app = require(appPath),
+ handler;
+
+ // Call our app handler in the req domain
+ if (app instanceof http.Server) {
+ // Express 2.x or Connect 1.x
+ if (app.handle) {
+ // Call it on the app so it can access `this.stack`
+ handler = function(req, res) {
+ app.handle(req, res);
+ };
+ }
+ // Raw HTTP Server
+ else {
+ handler = app._events.request;
+ }
+ }
+ // Express 3.x, Connect 2.x, or basic requestHandler
+ else if (typeof app === "function") {
+ handler = app;
+ }
+
+ // We didn't get a supported handler
+ if (!handler) {
+ console.error("App is not a recognized HTTP server");
+ serverDomain.dispose();
+ process.exit(1);
+ }
+
+ server = http.createServer(function(req, res) {
// Make a domain for this request
var reqd = domain.create();
@@ -20,7 +48,7 @@ module.exports = function(appPath) {
// Error handler
reqd.on('error', function(err) {
- console.error('Uncaught Exception', err.stack, req.url);
+ console.error('Uncaught Exception', err.stack || err, req.url);
try {
res.writeHead(500);
res.on('close', function() {
@@ -35,27 +63,12 @@ module.exports = function(appPath) {
res.end('A fatal error occured:\n'+(process.env.NODE_ENV=="development"?err.stack:""));
}
} catch (err) {
- console.error('Error sending 500', err.stack, req.url);
+ console.error('Error sending 500', err.stack || err, req.url);
reqd.dispose();
}
});
- // Call our app handler in the req domain
- if (app instanceof http.Server) {
- // Express 2.x or Connect 1.x
- if (app.handle) {
- // Call it on the app so it can access `this.stack`
- reqd.bind(function(_req, _res) {app.handle(_req, _res)})(req, res);
- }
- // Raw HTTP Server
- else {
- reqd.bind(app._events.request)(req, res);
- }
- }
- // Express 3.x, Connect 2.x, or basic requestHandler
- else {
- reqd.bind(app)(req, res);
- };
+ reqd.bind(handler)(req, res);
});
// TODO do we need to transfer properties from `app` to `server`?
@@ -66,5 +79,9 @@ module.exports = function(appPath) {
});
});
- return app;
+ serverDomain.on("error", function(err) {
+ console.error('Uncaught Exception', err.stack || err);
+ serverDomain.dispose();
+ if(server) server.close();
+ });
};

0 comments on commit 2f4baf9

Please sign in to comment.