-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathapp-worker.js
94 lines (83 loc) · 2.43 KB
/
app-worker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';
var util = require('util');
var worker = require('cluster').worker;
var domain = require('domain');
var config = require('./config');
var express = require('express');
var bodyParser = require('body-parser');
var logger = require('./lib/logger');
var app = express();
app.set('json spaces', 2);
app.use(bodyParser.json({ limit: 100000000 }));
app.use(function (req, res, next) {
logger.info({ url: req.url, method: req.method, headers: req.headers, query: req.query });
next();
});
app.use(uncaughtExceptionHandler);
app.use('/api', require('./routes/api'));
app.use(errorHandler);
var host = config.get('server:hostname');
var port = config.get('server:port');
var server = app.listen(port, host, function () {
logger.info(util.format('Node server started on %s:%d', host, port));
});
/**
* Expressjs middleware for handling errors.
* @function
* @name errorHandler
* @param {express.Request} req
* @param {express.Response} res
* @param {Function} next Express Middleware callback
*/
function errorHandler(err, req, res, next) {
logger.err(err);
var status = Number(err.status) || 500;
var message = err instanceof Error? {
status: 500,
title: 'Internal Error',
detail: err.stack || err.toString()
} : err;
if(!res.headersSent) {
res.status(status).jsonp({
data: null,
error: message
});
}
// next(err);
}
/**
* Expressjs middleware for handling uncaught exceptions with domain and worker restarting.
* @function
* @name uncaughtExceptionHandler
* @param {express.Request} req
* @param {express.Response} res
* @param {Function} next Express Middleware callback
*/
function uncaughtExceptionHandler(req, res, next) {
var d = domain.create();
d.add(req);
d.add(res);
d.on('error', function (err) {
logger.alert(err);
// Make sure we close down within 5 seconds.
var timer = setTimeout(function () {
process.exit(1);
}, 5000);
// But don't keep the process open just for that!
timer.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.
worker.disconnect();
// Try to send an error to the request that triggered the problem.
try {
errorHandler(err, req, res, next);
}
catch (err) {
// Oh well, not much we can do at this point.
logger.emerg(err);
}
});
d.run(next);
}