Skip to content

Commit 9825cef

Browse files
authored
Log unhandled errors that occur upon startup or handling HTTP requests (#179)
Whenever unhandled errors are raised, it's especially important for us to get some hints of what happened. In a perfect world these kinds of errors shouldn't happen, but ofcourse they do for time to time.. The last time we had this kinds of error, there were no errors visible in the logs, other than seeing that the bot process seemed to restart more than usual. While working in these changes, I found that the default unhandled error handler in express.js, writes the error to stdout, not into the log log files we've write through via bunyan. With these changes in place we'll get something like this in the logs: ``` 19:16:26.303Z FATAL bot: Unchaught exception, terminating bot process immediately ReferenceError: invokingNoneExistentFunction is not defined at Promise.resolve.then (/github-bot/app.js:47:31) at process._tickCallback (internal/process/next_tick.js:109:7) at Module.runMain (module.js:613:11) at run (bootstrap_node.js:387:7) at startup (bootstrap_node.js:153:9) at bootstrap_node.js:500:3 ``` Refs #174 /cc @nodejs/github-bot
1 parent 8fdb3db commit 9825cef

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

app.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,9 @@ glob.sync(scriptsToLoad).forEach((file) => {
3939
require(file)(app)
4040
})
4141

42+
app.use(function logUnhandledErrors (err, req, res, next) {
43+
logger.error(err, 'Unhandled error while responding to incoming HTTP request')
44+
res.status(500).end()
45+
})
46+
4247
module.exports = app

server.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,3 +39,13 @@ if (process.env.SSE_RELAY) {
3939
}
4040
}
4141
}
42+
43+
function logUnhandledException (err) {
44+
logger.fatal(err, 'Unchaught exception, terminating bot process immediately')
45+
46+
// leave time for error to be written to disk before exiting process
47+
setTimeout(() => process.exit(1), 10)
48+
}
49+
50+
process.on('uncaughtException', logUnhandledException)
51+
process.on('unhandledRejection', logUnhandledException)

0 commit comments

Comments
 (0)