PHP code example of middlewares / error-handler

1. Go to this page and download the library: Download middlewares/error-handler library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

middlewares / error-handler example snippets


use Middlewares\ErrorFormatter;
use Middlewares\ErrorHandler;
use Middlewares\Utils\Dispatcher;

// Create a new ErrorHandler instance
// Any number of formatters can be added. One will be picked based on the Accept
// header of the request. If no formatter matches, the first formatter in the array
// will be used.
$errorHandler = new ErrorHandler([
    new ErrorFormatter\HtmlFormatter(),
    new ErrorFormatter\ImageFormatter(),
    new ErrorFormatter\JsonFormatter(),
    new ErrorFormatter\PlainFormatter(),
    new ErrorFormatter\SvgFormatter(),
    new ErrorFormatter\XmlFormatter(),
]);

// ErrorHandler should always be the first middleware in the stack!
$dispatcher = new Dispatcher([
    $errorHandler,
    // ...
    function ($request) {
        throw HttpErrorException::create(404);
    }
]);

$request = $serverRequestFactory->createServerRequest('GET', '/');
$response = $dispatcher->dispatch($request);

$errorHandler = new ErrorHandler([
    new ErrorFormatter\HtmlFormatter(),
    new ErrorFormatter\JsonFormatter()
]);

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
    try {
        return $handler->handle($request);
    } catch (Throwable $exception) {
        $this->logger->critical('Uncaught {error}', [
            'error' => $exception->getMessage(),
            'exception' => $exception, // If you use Monolog, this is correct
        ]);

        // leave it for the middleware
        throw $exception;
    }
}

class PrettyPage implements StreamFactoryInterface
{
    public function createStream(string $content = ''): StreamInterface
    {
        return Factory::createStream('<strong>Pretty page</strong>');
    }

    public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface
    {
        // This is safe as the Middleware only uses createStream()
        throw new Exception('Not implemented');
    }

    public function createStreamFromResource($resource): StreamInterface
    {
        // This is safe as the Middleware only uses createStream()
        throw new Exception('Not implemented');
    }
}


$errorHandler = new ErrorHandler([
    new HtmlFormatter(
        null,
        new PrettyPage,
    ),
]);