Skip to content

Commit

Permalink
Call afterPerform in performInline on error (#773)
Browse files Browse the repository at this point in the history
This PR makes it so `worker.performInline` calls Plugins' `afterPerform`
method when the `perform` function throws an error.
  • Loading branch information
stellarhoof committed Mar 21, 2022
1 parent da541e6 commit 23f7cc6
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
42 changes: 41 additions & 1 deletion __tests__/core/worker.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
import { ParsedFailedJobPayload, Job, Queue, Worker } from "../../src";
import { ParsedFailedJobPayload, Job, Queue, Worker, Plugin } from "../../src";
import specHelper from "../utils/specHelper";

class MyPlugin extends Plugin {
async beforeEnqueue() {
return true;
}
async afterEnqueue() {
return true;
}
async beforePerform() {
return true;
}
async afterPerform() {
this.options.afterPerform(this);
return true;
}
}

const jobs: { [key: string]: Job<any> } = {
add: {
perform: (a, b) => {
Expand Down Expand Up @@ -88,6 +104,30 @@ describe("worker", () => {
expect(String(error)).toBe("Error: Blue Smoke");
}
});

test("can call a Plugin's afterPerform given the job throws an error", async () => {
let actual = null;
let expected = new TypeError("John");

let failingJob = {
plugins: [MyPlugin],
pluginOptions: {
MyPlugin: {
afterPerform: (plugin: Plugin) => {
actual = plugin.worker.error;
delete plugin.worker.error;
},
},
},
perform: (x: string) => {
throw new TypeError(x);
},
};
let worker = new Worker({}, { failingJob });
await worker.performInline("failingJob", ["John"]);

expect(actual).toEqual(expected);
});
});

describe("[with connection]", () => {
Expand Down
21 changes: 20 additions & 1 deletion src/core/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,7 @@ export class Worker extends EventEmitter {
throw new Error(`Missing Job: "${func}"`);
}

let triedAfterPerform = false;
try {
toRun = await RunPlugins(
this,
Expand All @@ -350,6 +351,7 @@ export class Worker extends EventEmitter {
return;
}
this.result = await this.jobs[func].perform.apply(this, args);
triedAfterPerform = true;
toRun = await RunPlugins(
this,
"afterPerform",
Expand All @@ -361,7 +363,24 @@ export class Worker extends EventEmitter {
return this.result;
} catch (error) {
this.error = error;
throw error;
if (!triedAfterPerform) {
try {
await RunPlugins(
this,
"afterPerform",
func,
this.queue,
this.jobs[func],
args
);
} catch (error) {
if (error && !this.error) {
this.error = error;
}
}
}
// Allow afterPerform to clear the error
if (this.error) throw this.error;
}
}

Expand Down

0 comments on commit 23f7cc6

Please sign in to comment.