-1

I have a fairly simple NodeJs server script, that handles incoming data and persists it to a database. The script runs indefinitely. Mostly this works great, but sometimes an error arrises. Is there a way to listen for an exception and if the script was terminated to rerun it again?

(I know the issues for causing the exception must be fixed, and I've done that, but I want to be sure the script always runs as I otherwise loose valuable data; the use case lies in processing IoT sensor data)

Ben Fransen
  • 10,884
  • 18
  • 76
  • 129
  • Are you `try/catch`ing your problematic portion of code? Would be great to see it in order to help! – moonwave99 Sep 04 '22 at 08:49
  • Does [this](https://www.npmjs.com/package/pm2) help? Also, it is always important to handle [unhandled exceptions](https://stackoverflow.com/questions/7310521/node-js-best-practice-exception-handling). – Apoorva Chikara Sep 04 '22 at 08:57
  • you can use https://nodejs.org/api/cluster.html#cluster. – ben Sep 04 '22 at 09:00

1 Answers1

1

It seems like you have an uncaught exception that causes your application to crash.

First of all, you should use try...catch statements to catch exceptions where they can appear within your range of responsibilities. If you don't care about proper error handling and just want to make sure the application keeps running, it is as simple as the following. This way, errors won't bubble up becoming uncaught exceptions to crash your application:

try {
  // logic prone to errors
} catch (error) {}

If your application somehow can come into an erroneous state which is unpredictable and hard to resolve during runtime, you can use solutions like process managers, PM2 for instance, to automatically restart your application in case of errors.

alexanderdavide
  • 1,487
  • 3
  • 14
  • 22
  • Thank you for your reply and suggestions. I've updated the code to leverage try-catch and will look into pm2 - as also suggested by moonwave99 and apoorva chikara – Ben Fransen Sep 05 '22 at 13:02