Search code examples
phplaravellaravel-11laravel-exceptions

Handling Exceptions inside Pipeline


I'am kind of new to laravel and currently working with pipelines. As I know, if one step inside the Pipeline fail, the whole Pipeline get stopped at that step. That is exactly what I want, so I'am fine with that.

But I want to handle the given Exception from the failing step. And now is the question, how? I can't find anything about that..

So my code for the pipeline looks like this (e.g.):

final readonly class CreateInboundPlanPipeline
{
    public function __invoke(DataContainer $container, Closure $next): DataContainer
    {
        //Init Normalizer
        $normalizer = new FBAInboundNormalizer();

        //Do something with $container
        $items = json_decode($container->__get('initialrequest')->input('items'));
        $response = $normalizer->createInboundPlan($items, $container->__get('initialrequest'));

        if($response['success']){
            $extendContainer = $container;
            $extendContainer->inboundplanid = $response["inboundPlanId"];
            $extendContainer->currentOperationId = $response["operationId"];
        }else{
            throw new \Exception($response["message"]);
        }

        return $next($extendContainer);
    }   
}


public function handle(): void
{
    $filledContainer = app(Pipeline::class)
    ->send($this->container)
    ->through([
        CreateInboundPlanPipeline::class,
    ])
    ->then(function(){
        //Action after Pipeline
        //e.g. fill a model or smth
    });
}

E.g. if "CreateInboundPlanPipeline" throws an Exception, how could I catch and handle it? I found the function "handleException" inside the Pipeline, is that the proper way? Would look like this?

$filledContainer = app(Pipeline::class)
        ->send($this->container)
        ->through([
            CreateInboundPlanPipeline::class,
        ])
        ->then(function(){
            //Action after Pipeline
            //e.g. fill a model or smth
        })
        ->handleException(function(){
            //Handle Exception here
        });

Solution

  • You should be able to try/catch the pipeline.

    use Illuminate\Support\Facades\Pipeline;
    
    try{
    
        $data = Pipeline::send($whatever)
            ->through([
                TaskOne::class,
                TaskTwo::class
            ])
            ->thenReturn();
    
    }catch(MyException $e){
        
        // Handle however you want
    }