I am using openode.io to host a nodejs application. I am running a multiplayer server on it. Sometimes, due to lag or user disconnection, the process will emit an uncaught error and it crashes. I have fixed some of these errors, but at any point in time, if a user sends invalid data, my process will crash. I researched how to prevent this and got Sentry to log errors and used the following code at the beginning of the nodejs process to prevent crashes:
// prevent crashes
process.on('unhandledRejection', (reason, p) => {
logger.info(reason + ' => Unhandled Rejection at Promise: ' + p);
logger.info('!!!FATAL!!!')
})
process.on('uncaughtException', err => {
logger.info(err + ' => Uncaught Exception thrown');
logger.info('!!!FATAL!!!');
});
I decided to do a test run, by using a common error that occurs on my server.
TypeError: Cannot set property 'canTakeThermalDamage' of undefined
File "/opt/app/server.js", line 579, col 45, in Timeout._onTimeout
host.pt[l].canTakeThermalDamage = true;
File "internal/timers.js", line 559, col 11, in listOnTimeout
File "internal/timers.js", line 500, col 7, in processTimers
This error should not have crashed the process, but it did. Since this happens on a multiplayer server, EVERY single user on it gets disconnected and has to log in again. Here are the sentry logs about the error: When this error happens, the code inside process.on runs, but the process still crashes? Is Sentry crashing it because it found an error? Is the error caused by the setTimeout? Or is there another reason?
Anyway the process will exit. It just give you some options to do cleanup.
By default, Node.js handles such exceptions by printing the stack trace to stderr and exiting with code 1
When you add your own handler (this is your case):
Alternatively, change the process.exitCode in the 'uncaughtException' handler which will result in the process exiting with the provided exit code. Otherwise, in the presence of such handler the process will exit with 0. You can register a listener for
unhandledRejection
to do some cleanup before exiting.
uncaughtException
handler always exit the process with process.exit(1)
unless you have a very good reason not to