Skip to content

Commit

Permalink
Catch unexpected errors and exit app gracefully
Browse files Browse the repository at this point in the history
  • Loading branch information
hagopj13 committed Oct 27, 2019
1 parent 50939f4 commit 9cfcd02
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,28 @@ const app = require('./app');
const logger = require('./config/logger');
const config = require('./config/config');

let server;
app.on('ready', () => {
app.listen(config.port, () => {
server = app.listen(config.port, () => {
logger.info(`Listening to port ${config.port}`);
});
});

const exitHandler = () => {
if (server) {
server.close(() => {
logger.info('Server closed');
process.exit(1);
});
} else {
process.exit(1);
}
};

const unexpectedErrorHandler = error => {
logger.error(`Unexpected error ${error}`);
exitHandler();
};

process.on('uncaughtException', unexpectedErrorHandler);
process.on('unhandledRejection', unexpectedErrorHandler);

0 comments on commit 9cfcd02

Please sign in to comment.