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.
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.
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.
nodejs-try-catch-example.js readFileSync('sample. html'); } catch (err){ console. log(err); } console. log("Continuing with other statements..");
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.
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); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With