master

laravel/framework

Last updated at: 29/12/2023 09:24

Pipeline.php

TLDR

The provided file, Pipeline.php, is an extended pipeline class that catches exceptions that occur during each slice and handles them by converting them to HTTP responses for proper middleware handling.

Methods

handleCarry

This method handles the value returned from each pipe before passing it to the next pipe. If the value returned is an instance of Responsable, it calls the toResponse method on the value passing in an instance of Request and returns the response. Otherwise, it returns the value as is.

handleException

This method handles the given exception. If the container is bound to an ExceptionHandler class and the passable is an instance of Request, it reports the exception to the handler, renders the response using the handler, and then checks if the response object has a withException method. If it does, it calls the method passing in the exception. Finally, it returns the response after handling it with handleCarry.

Class

Illuminate\Routing\Pipeline

This class extends the Illuminate\Pipeline\Pipeline class and adds functionality for handling exceptions that occur during each pipeline slice. It catches exceptions, reports them to the exception handler, renders the response using the handler, and converts the response into a proper middleware handling format.

<?php

namespace Illuminate\Routing;

use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Contracts\Support\Responsable;
use Illuminate\Http\Request;
use Illuminate\Pipeline\Pipeline as BasePipeline;
use Throwable;

/**
 * This extended pipeline catches any exceptions that occur during each slice.
 *
 * The exceptions are converted to HTTP responses for proper middleware handling.
 */
class Pipeline extends BasePipeline
{
    /**
     * Handles the value returned from each pipe before passing it to the next.
     *
     * @param  mixed  $carry
     * @return mixed
     */
    protected function handleCarry($carry)
    {
        return $carry instanceof Responsable
            ? $carry->toResponse($this->getContainer()->make(Request::class))
            : $carry;
    }

    /**
     * Handle the given exception.
     *
     * @param  mixed  $passable
     * @param  \Throwable  $e
     * @return mixed
     *
     * @throws \Throwable
     */
    protected function handleException($passable, Throwable $e)
    {
        if (! $this->container->bound(ExceptionHandler::class) ||
            ! $passable instanceof Request) {
            throw $e;
        }

        $handler = $this->container->make(ExceptionHandler::class);

        $handler->report($e);

        $response = $handler->render($passable, $e);

        if (is_object($response) && method_exists($response, 'withException')) {
            $response->withException($e);
        }

        return $this->handleCarry($response);
    }
}