Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: error handling on ticks #861

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,8 @@ day of week 0-7 (0 or 7 is Sunday, or use names)

- `unrefTimeout`: [OPTIONAL] - Useful for controlling event loop behavior. More details [here](https://nodejs.org/api/timers.html#timers_timeout_unref).

- `errorHandler`: [OPTIONAL] - Function to handle any exceptions that occur in the `onTick` method.

#### Methods

- `from` (static): Create a new CronJob object providing arguments as an object. See argument names and descriptions above.
Expand Down
38 changes: 26 additions & 12 deletions src/job.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {
onComplete?: WithOnComplete<OC> extends true
? CronOnCompleteCallback
: undefined;
errorHandler?: CronJobParams<OC, C>['errorHandler'];
JosephVoid marked this conversation as resolved.
Show resolved Hide resolved

private _timeout?: NodeJS.Timeout;
private _callbacks: CronCallback<C, WithOnComplete<OC>>[] = [];
Expand All @@ -34,7 +35,8 @@ export class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {
context?: CronJobParams<OC, C>['context'],
runOnInit?: CronJobParams<OC, C>['runOnInit'],
utcOffset?: null,
unrefTimeout?: CronJobParams<OC, C>['unrefTimeout']
unrefTimeout?: CronJobParams<OC, C>['unrefTimeout'],
errorHandler?: CronJobParams<OC, C>['errorHandler']
);
constructor(
cronTime: CronJobParams<OC, C>['cronTime'],
Expand All @@ -45,7 +47,8 @@ export class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {
context?: CronJobParams<OC, C>['context'],
runOnInit?: CronJobParams<OC, C>['runOnInit'],
utcOffset?: CronJobParams<OC, C>['utcOffset'],
unrefTimeout?: CronJobParams<OC, C>['unrefTimeout']
unrefTimeout?: CronJobParams<OC, C>['unrefTimeout'],
errorHandler?: CronJobParams<OC, C>['errorHandler']
);
constructor(
cronTime: CronJobParams<OC, C>['cronTime'],
Expand All @@ -56,10 +59,13 @@ export class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {
context?: CronJobParams<OC, C>['context'],
runOnInit?: CronJobParams<OC, C>['runOnInit'],
utcOffset?: CronJobParams<OC, C>['utcOffset'],
unrefTimeout?: CronJobParams<OC, C>['unrefTimeout']
unrefTimeout?: CronJobParams<OC, C>['unrefTimeout'],
errorHandler?: CronJobParams<OC, C>['errorHandler']
) {
this.context = (context ?? this) as CronContext<C>;

this.errorHandler = errorHandler;

// runtime check for JS users
if (timeZone != null && utcOffset != null) {
throw new ExclusiveParametersError('timeZone', 'utcOffset');
Expand Down Expand Up @@ -117,7 +123,8 @@ export class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {
params.context,
params.runOnInit,
params.utcOffset,
params.unrefTimeout
params.unrefTimeout,
params.errorHandler
);
} else if (params.utcOffset != null) {
return new CronJob<OC, C>(
Expand All @@ -129,7 +136,8 @@ export class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {
params.context,
params.runOnInit,
params.utcOffset,
params.unrefTimeout
params.unrefTimeout,
params.errorHandler
);
} else {
return new CronJob<OC, C>(
Expand All @@ -141,7 +149,8 @@ export class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {
params.context,
params.runOnInit,
params.utcOffset,
params.unrefTimeout
params.unrefTimeout,
params.errorHandler
);
}
}
Expand Down Expand Up @@ -195,12 +204,17 @@ export class CronJob<OC extends CronOnCompleteCommand | null = null, C = null> {

fireOnTick() {
for (const callback of this._callbacks) {
void callback.call(
this.context,
this.onComplete as WithOnComplete<OC> extends true
? CronOnCompleteCallback
: never
);
try {
void callback.call(
this.context,
this.onComplete as WithOnComplete<OC> extends true
? CronOnCompleteCallback
: never
);
} catch (error: unknown) {
if (this.errorHandler != null) this.errorHandler(error);
else throw error;
}
}
}

Expand Down
1 change: 1 addition & 0 deletions src/types/cron.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ interface BaseCronJobParams<
context?: C;
runOnInit?: boolean | null;
unrefTimeout?: boolean | null;
errorHandler?: ((error: unknown) => void) | null;
}

export type CronJobParams<
Expand Down
38 changes: 38 additions & 0 deletions tests/cron.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1238,4 +1238,42 @@ describe('cron', () => {
clock.restore();
expect(callback).toHaveBeenCalledTimes(1);
});

it('should catch errors everytime, if errorHandler is provided', () => {
const clock = sinon.useFakeTimers();
const errorFunc = jest.fn().mockImplementation(() => {
throw Error('Exception');
});
const handlerFunc = jest.fn();
const job = CronJob.from({
cronTime: '* * * * * *',
onTick: errorFunc,
errorHandler: handlerFunc,
start: true
});
clock.tick(1000);
expect(errorFunc).toHaveBeenCalledTimes(1);
expect(handlerFunc).toHaveBeenCalledTimes(1);
expect(handlerFunc).toHaveBeenLastCalledWith(new Error('Exception'));
clock.tick(1000);
expect(errorFunc).toHaveBeenCalledTimes(2);
expect(handlerFunc).toHaveBeenCalledTimes(2);
expect(handlerFunc).toHaveBeenLastCalledWith(new Error('Exception'));

job.stop();
clock.restore();
});

it('should throw errors if errorHandler is NOT provided', () => {
const errorFunc = jest.fn().mockImplementation(() => {
throw Error('Exception');
});
expect(() => {
CronJob.from({
cronTime: '* * * * * *',
onTick: errorFunc,
runOnInit: true
});
}).toThrow('Exception');
});
});