Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch all uncaughtException for Node js app

I have a question: how do I can handle all uncaught Exception (operations/developer error will take all service down) for my node app. Then I can send an email alert to me whenever catch an error.

like image 908
Nam Tran Thanh Avatar asked Nov 29 '16 13:11

Nam Tran Thanh


People also ask

How do you catch Uncaughtexception?

Instead, the best way to handle it is to have your program crash, log the crash (and the stack/core dump), then restart it automatically, using pm2 or nodemon. Edit: A bit more details and an attempt at solving your issue. Using a software like pm2 to restart your app on crash, you will also be able to see the error.

How do you catch specific errors in node JS?

Using try-catch-finally. js, you can call the _try function with an anonymous callback, which it will call, and you can chain . catch calls to catch specific errors, and a . finally call to execute either way.

How do you run a catch block in node JS?

nodejs-try-catch-example.js readFileSync('sample. html'); } catch (err){ console. log(err); } console. log("Continuing with other statements..");

What is process nextTick in node JS?

When in Node JS, one iteration of the event loop is completed. This is known as a tick. process. nextTick() taking a callback function which is executed after completing the current iteration/tick of the event loop.


1 Answers

You can use process 'uncaughtException' and 'unhandledRejection' events.

Also remember that it is not safe to resume normal operation after 'uncaughtException', because the system becomes corrupted:

The correct use of 'uncaughtException' is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting down the process.

Example:

process   .on('unhandledRejection', (reason, p) => {     console.error(reason, 'Unhandled Rejection at Promise', p);   })   .on('uncaughtException', err => {     console.error(err, 'Uncaught Exception thrown');     process.exit(1);   }); 
like image 57
Dario Avatar answered Sep 21 '22 03:09

Dario