From ebaa3fb31708e1d46e2b8b454cc779340bc0cb97 Mon Sep 17 00:00:00 2001 From: Julian Hundeloh <5358638+jaulz@users.noreply.github.com> Date: Sat, 9 Nov 2024 20:58:38 +0100 Subject: [PATCH] fix: handle errors in closures (#17) * fix: handle errors in closures * test: add test --- src/JobPipeline.php | 2 +- tests/JobPipelineTest.php | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/JobPipeline.php b/src/JobPipeline.php index 2781ef0..137f34e 100644 --- a/src/JobPipeline.php +++ b/src/JobPipeline.php @@ -72,7 +72,7 @@ class JobPipeline implements ShouldQueue try { $result = app()->call($job); } catch (Throwable $exception) { - if (method_exists(get_class($job[0]), 'failed')) { + if (is_array($job) && method_exists(get_class($job[0]), 'failed')) { call_user_func_array([$job[0], 'failed'], [$exception]); } else { throw $exception; diff --git a/tests/JobPipelineTest.php b/tests/JobPipelineTest.php index bf8d1a5..29d6ca8 100644 --- a/tests/JobPipelineTest.php +++ b/tests/JobPipelineTest.php @@ -2,6 +2,7 @@ namespace Stancl\JobPipeline\Tests; +use Exception; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Queue; @@ -193,6 +194,22 @@ class JobPipelineTest extends TestCase $this->assertTrue($passes); } + + /** @test */ + public function failures_in_closures_will_throw_correctly() + { + $this->expectExceptionMessage('foobar'); + + Event::listen(TestEvent::class, JobPipeline::make([ + function () { + throw new Exception('foobar'); + } + ])->send(function (TestEvent $event) { + return $this->valuestore; + })->shouldBeQueued(false)->toListener()); + + event(new TestEvent(new TestModel())); + } } class FooJob