summaryrefslogtreecommitdiff
path: root/src/node/hooks/express/errorhandling.js
blob: 7afe80aeba736f52d58ea6eb0cefb709f8210c7e (plain)
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
var os = require("os");
var db = require('../../db/DB');
var stats = require('ep_etherpad-lite/node/stats')


exports.onShutdown = false;
exports.gracefulShutdown = function(err) {
  if(err && err.stack) {
    console.error(err.stack);
  } else if(err) {
    console.error(err);
  }

  //ensure there is only one graceful shutdown running
  if(exports.onShutdown) return;
  exports.onShutdown = true;

  console.log("graceful shutdown...");

  //do the db shutdown
  db.db.doShutdown(function() {
    console.log("db sucessfully closed.");

    process.exit(0);
  });

  setTimeout(function(){
    process.exit(1);
  }, 3000);
}

process.on('uncaughtException', exports.gracefulShutdown);

exports.expressCreateServer = function (hook_name, args, cb) {
  exports.app = args.app;

  // Handle errors
  args.app.use(function(err, req, res, next){
    // if an error occurs Connect will pass it down
    // through these "error-handling" middleware
    // allowing you to respond however you like
    res.status(500).send({ error: 'Sorry, something bad happened!' });
    console.error(err.stack? err.stack : err.toString());
    stats.meter('http500').mark()
  })

  //connect graceful shutdown with sigint and uncaughtexception
  if(os.type().indexOf("Windows") == -1) {
    //sigint is so far not working on windows
    //https://github.com/joyent/node/issues/1553
    process.on('SIGINT', exports.gracefulShutdown);
  }
}