Skip to content

Commit 95f8468

Browse files
authored
Merge pull request #395 from msheakoski/catch-job-exception
Clean up when a job triggers an exception
2 parents 834ea8e + de87500 commit 95f8468

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

pkg/job-queue/JobRunner.php

+11-1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ public function __construct(JobProcessor $jobProcessor, Job $rootJob = null)
2929
* @param string $name
3030
* @param callable $runCallback
3131
*
32+
* @throws \Throwable|\Exception if $runCallback triggers an exception
33+
*
3234
* @return mixed
3335
*/
3436
public function runUnique($ownerId, $name, callable $runCallback)
@@ -46,7 +48,15 @@ public function runUnique($ownerId, $name, callable $runCallback)
4648

4749
$jobRunner = new self($this->jobProcessor, $rootJob);
4850

49-
$result = call_user_func($runCallback, $jobRunner, $childJob);
51+
try {
52+
$result = call_user_func($runCallback, $jobRunner, $childJob);
53+
} catch (\Throwable $e) {
54+
$this->jobProcessor->failChildJob($childJob);
55+
throw $e;
56+
} catch (\Exception $e) { // needed to support PHP 5.6
57+
$this->jobProcessor->failChildJob($childJob);
58+
throw $e;
59+
}
5060

5161
if (!$childJob->getStoppedAt()) {
5262
$result

pkg/job-queue/Tests/JobRunnerTest.php

+32
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,38 @@ public function testRunUniqueShouldFailJobIfCallbackReturnValueIsFalse()
163163
});
164164
}
165165

166+
public function testRunUniqueShouldFailJobIfCallbackThrowsException()
167+
{
168+
$root = new Job();
169+
$child = new Job();
170+
171+
$jobProcessor = $this->createJobProcessorMock();
172+
$jobProcessor
173+
->expects($this->once())
174+
->method('findOrCreateRootJob')
175+
->will($this->returnValue($root))
176+
;
177+
$jobProcessor
178+
->expects($this->once())
179+
->method('findOrCreateChildJob')
180+
->will($this->returnValue($child))
181+
;
182+
$jobProcessor
183+
->expects($this->never())
184+
->method('successChildJob')
185+
;
186+
$jobProcessor
187+
->expects($this->once())
188+
->method('failChildJob')
189+
;
190+
191+
$jobRunner = new JobRunner($jobProcessor);
192+
$this->expectException(\Exception::class);
193+
$jobRunner->runUnique('owner-id', 'job-name', function () {
194+
throw new \Exception();
195+
});
196+
}
197+
166198
public function testRunUniqueShouldNotSuccessJobIfJobIsAlreadyStopped()
167199
{
168200
$root = new Job();

0 commit comments

Comments
 (0)