node-cron icon indicating copy to clipboard operation
node-cron copied to clipboard

Exception thrown inside scheduled task is silently swallowed

Open avillacis opened this issue 3 years ago • 3 comments

If the function or closure passed as a parameter of the cron.schedule happens to throw an exception anywhere, and is not properly catched withing the body of the function, the library swallows the exception silently with no indication as to whether an exception has happened. This makes debugging more difficult.

The library should catch and dump the unhandled exception. Failing that, this caveat should be documented in the manual so the programmer can guard against it from the very start.

avillacis avatar Mar 07 '23 16:03 avillacis

Meanwhile, croner has an option to control this - (catch), which takes true to silently swallow, false to re-throw, or a callback function if you want to handle the error in a more controlled way. See https://github.com/Hexagon/croner/blob/master/docs/EXAMPLES.md#error-handling for an example

Hexagon avatar Mar 12 '23 22:03 Hexagon

I've also been running into this issue, I've spent a lot of time debugging one of my scheduled tasks that seemingly stopped in the middle of executing - turns out it was throwing an exception and just stopping.

zimmerry avatar May 11 '23 18:05 zimmerry

I did a workaround for async tasks by using a wrapper function:

function scheduleAsyncCron(expression, fn, options) {
  cron.schedule(expression, () => fn().catch((e) => console.error(e)), options);
}

scheduleAsyncCron('* * * * *', async () => {
  await asyncFunctionToRun();
});

samuliasmala avatar Aug 10 '23 13:08 samuliasmala