Skip to content

Commit c4de8fb

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

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-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: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use PHPUnit\Framework\TestCase;
88
use RuntimeException;
99
use stdClass;
10+
use \Exception;
1011

1112
class PipelineTest extends TestCase
1213
{
@@ -231,6 +232,20 @@ public function testPipelineThrowsExceptionOnResolveWithoutContainer()
231232
});
232233
}
233234

235+
public function testExceptionIsHandledByOnFailureMethodInPipeline()
236+
{
237+
$result = (new Pipeline(new Container))
238+
->send('data')
239+
->through(PipelineWithException::class)
240+
->onFailure(function (){
241+
return 'error';
242+
})->then(function ($piped) {
243+
return $piped;
244+
});
245+
246+
$this->assertEquals('error', $result);
247+
}
248+
234249
public function testPipelineThenReturnMethodRunsPipelineThenReturnsPassable()
235250
{
236251
$result = (new Pipeline(new Container))
@@ -279,3 +294,11 @@ public function handle($piped, $next, $parameter1 = null, $parameter2 = null)
279294
return $next($piped);
280295
}
281296
}
297+
298+
class PipelineWithException
299+
{
300+
public function handle($piped, $next)
301+
{
302+
throw new Exception('Foo');
303+
}
304+
}

0 commit comments

Comments
 (0)