Skip to content

Commit f3503c5

Browse files
committed
[9.x] Add onFailure method to Pipeline
1 parent c5c97e4 commit f3503c5

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/Illuminate/Pipeline/Pipeline.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ class Pipeline implements PipelineContract
2424
*/
2525
protected $passable;
2626

27+
/**
28+
* The callback to be executed on failure pipeline.
29+
*
30+
* @var Closure
31+
*/
32+
protected $onFailure;
33+
2734
/**
2835
* The array of class pipes.
2936
*
@@ -182,6 +189,10 @@ protected function carry()
182189

183190
return $this->handleCarry($carry);
184191
} catch (Throwable $e) {
192+
if ($this->onFailure) {
193+
return call_user_func($this->onFailure, $pipe);
194+
}
195+
185196
return $this->handleException($passable, $e);
186197
}
187198
};
@@ -244,6 +255,19 @@ public function setContainer(Container $container)
244255
return $this;
245256
}
246257

258+
/**
259+
* Set callback to be executed on failure pipeline.
260+
*
261+
* @param Closure $catch
262+
* @return $this
263+
*/
264+
public function onFailure(Closure $callback)
265+
{
266+
$this->onFailure = $callback;
267+
268+
return $this;
269+
}
270+
247271
/**
248272
* Handle the value returned from each pipe before passing it to the next.
249273
*

tests/Pipeline/PipelineTest.php

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,20 @@ public function testPipelineThrowsExceptionOnResolveWithoutContainer()
231231
});
232232
}
233233

234+
public function testExceptionIsHandledByOnFailureMethodInPipeline()
235+
{
236+
$result = (new Pipeline(new Container))
237+
->send('data')
238+
->through(PipelineWithException::class)
239+
->onFailure(function () {
240+
return 'error';
241+
})->then(function ($piped) {
242+
return $piped;
243+
});
244+
245+
$this->assertEquals('error', $result);
246+
}
247+
234248
public function testPipelineThenReturnMethodRunsPipelineThenReturnsPassable()
235249
{
236250
$result = (new Pipeline(new Container))
@@ -279,3 +293,11 @@ public function handle($piped, $next, $parameter1 = null, $parameter2 = null)
279293
return $next($piped);
280294
}
281295
}
296+
297+
class PipelineWithException
298+
{
299+
public function handle($piped, $next)
300+
{
301+
throw new \Exception('Foo');
302+
}
303+
}

0 commit comments

Comments
 (0)