My NodeJs app forks 10 child processes on the start.
In every child process I have the next code:
process.on('unhandledRejection', (reason, promise) => {
log.error('Unhandled Rejection at:', promise, 'reason:', reason);
}).on('message', (message: any) => {
if (message.type === 'error') {
log.error(`Message error event: ${message}`);
}
})
.on('uncaughtException', (err: any) => {
log.error('Uncaught Exception thrown', err);
log.error(err.stack);
process.exit(1);
}).on('SIGINT', async () => {
log.info('SIGINT signal received.');
process.exit(0);
}).on('exit', async (code) => {
log.info(`Process exit with code: ${code}`);
process.exit(code);
});
My problem is when unhandled exception happens it doesn’t catch it.
If I deploy my app via pm2 – I can see nothing only Forked 432637 is exited with code 1
that I catch in the next code:
forked.on('exit', (code) => {
log.error(`Forked ${forked.pid} is exited with code ${code}. Restarting... in ${RESTART_TIMEOUT_IN_MILISECONDS} ms`);
});
If I deploy my app like npm run start
then I see the next error:
TypeError: this.log is not a function
at Logger.<computed> (/home/myapp/node_modules/log4js/lib/logger.js:235:10)
at Client.emit (node:events:514:28)
at emitUnhandledRejectionOrErr (node:events:395:10)
at process.processTicksAndRejections (node:internal/process/task_queues:84:21)
But I know it is not related to logs.
How can I catch this unhandled error? Preferable solution when I deploy via pm2.