Skip to content

Commit 784d0c5

Browse files
author
tombertrand
committed
Add terminate server
1 parent 8f2fb1e commit 784d0c5

File tree

3 files changed

+28
-16
lines changed

3 files changed

+28
-16
lines changed

server/sentry.js

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,22 +11,6 @@ Sentry.init({
1111
},
1212
});
1313

14-
process.on("uncaughtException", err => {
15-
console.log("Error", err);
16-
Sentry.captureException(err);
17-
});
18-
19-
process.on("exit", code => {
20-
Sentry.captureException(new Error("Exiting with code"), { extra: { code } });
21-
process.exit(code);
22-
});
23-
24-
process.on("unhandledRejection", (reason, promise) => {
25-
Sentry.captureException(new Error("Unhandled promise rejection"), {
26-
extra: { reason, promise },
27-
});
28-
});
29-
3014
module.exports = {
3115
Sentry,
3216
};

server/server.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ const { getTelemetry } = require("./api/telemetry");
6060
const { getRepresentative, getAllRepresentatives } = require("./api/representative");
6161
const { Sentry } = require("./sentry");
6262
const { isValidAccountAddress } = require("./utils");
63+
const { terminate } = require("./terminate");
6364

6465
const app = express();
6566
app.use(
@@ -316,4 +317,10 @@ app.get("*", (req, res, next) => {
316317
const server = app.listen(process.env.SERVER_PORT);
317318
server.timeout = 20000;
318319

320+
const exitHandler = terminate(server);
321+
process.on("uncaughtException", exitHandler(1, "Unexpected Error"));
322+
process.on("unhandledRejection", exitHandler(1, "Unhandled Promise"));
323+
process.on("SIGTERM", exitHandler(0, "SIGTERM"));
324+
process.on("SIGINT", exitHandler(0, "SIGINT"));
325+
319326
console.log(`Server started on http://localhost:${process.env.SERVER_PORT}`);

server/terminate.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const { Sentry } = require("./sentry");
2+
3+
function terminate(server, options = { coredump: false, timeout: 500 }) {
4+
const exit = code => {
5+
options.coredump ? process.abort() : process.exit(code);
6+
};
7+
8+
return (code, reason) => (err, promise) => {
9+
if (err && err instanceof Error) {
10+
Sentry.captureException(err);
11+
}
12+
13+
// Attempt a graceful shutdown
14+
server.close(exit);
15+
setTimeout(exit, options.timeout).unref();
16+
};
17+
}
18+
19+
module.exports = {
20+
terminate,
21+
};

0 commit comments

Comments
 (0)