Hexagon / croner

Trigger functions or evaluate cron expressions in JavaScript or TypeScript. No dependencies. Most features. Node. Deno. Bun. Browser.
https://croner.56k.guru
MIT License
2.02k stars 51 forks source link

[Feature Request] Add ability to specify own error handler #154

Closed MZPL closed 1 year ago

MZPL commented 1 year ago

Hello. I'm a new user of this library, and I'm looking forward to migrate from node-cron to croner. I've noticed there's no way to catch and log errors besides putting the whole code in the try..catch. This works, but it's not really convenient. I looked through the README and found catch: true option, but unfortunately, it only catches any potential errors and suppresses them. My suggestion would be to allow passing a function to the catch property, which would then be called if an error throws, e.g { catch: (err) => console.error(err) }.

Hexagon commented 1 year ago

Will have a look at that 👍

Hexagon commented 1 year ago

Released in 5.4.0 - give it a go!

Example (running on Deno):

import Cron from "https://deno.land/x/croner@5.4.0/dist/croner.min.mjs";

const onError = (e) => console.error('Oh shit - ', e);

Cron("* * * * * *", { catch: onError },
    () => {
        console.log("This will run every second.");
        throw new Error("t");
    }
);
MZPL commented 1 year ago

Thanks, I didn't expect to see it released that quickly! I'm using TypeScript and I noticed a small typing issue:

cron("* * * * * *", () => {
    throw new Error("err!");
  },
  {
    // TS7006: Parameter 'e' implicitly has an 'any' type. (appears if strict mode is enabled)
    // Can be fixed by adding `e: any`
    catch(e) {
      console.error("Error!", e);
    },
  }
);

It'd be beneficial for TS users to define the arguments explicitly, so the compiler knows there's an error parameter: catch?: boolean | ((error: unknown) => void);

Hexagon commented 1 year ago

Thanks for reporting (again)! Will have a look at that for 5.4.1.

Hexagon commented 1 year ago

(Hopefully) resolved in 5.4.1 which will be released any minute 👍

MZPL commented 1 year ago

(Hopefully) resolved in 5.4.1 which will be released any minute +1

Yep, I can confirm it's fixed. Thanks!