davidecesarano/embryo-error

PSR-15 middleware to handle errors.

1.0.4 2021-06-11 09:33 UTC

This package is auto-updated.

Last update: 2024-03-11 15:47:13 UTC


README

PSR-15 middleware to handle errors. This handler inspired by Slim. It receives all uncaught PHP exceptions and converts them to a new HTTP response with the status code.

Requirements

Install

Using Composer:

$ composer require davidecesarano/embryo-error

Usage

You may quickly test this using the built-in PHP server going to http://localhost:8000.

use Embryo\Error\ErrorHandler;
use Embryo\Error\Middleware\ErrorHandlerMiddleware;
use Embryo\Http\Factory\{ResponseFactory, ServerRequestFactory};
use Embryo\Http\Server\RequestHandler;
use Embryo\Log\StreamLogger;
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
use Psr\Http\Server\{MiddlewareInterface, RequestHandlerInterface};

// Set path log files and stream logger
$logPath = '/path/to/logs';
$logger = new StreamLogger($logPath);

// Set error handler
$errorHandler = (new ErrorHandler)->setLogger($logger);

// Set PSR Request and Response
$request = (new ServerRequestFactory)->createServerRequestFromServer();
$response = (new ResponseFactory)->createResponse(200);

// Set custom middleware with exception
class TestMiddleware implements MiddlewareInterface
{
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        throw new \Exception('This is a test error!');
    }
}

// ErrorHandler should always be the first middleware in the stack!
$middleware = new RequestHandler([
    (new ErrorHandlerMiddleware)->setErrorHandler($errorHandler),
    new TestMiddleware
]);


$response = $middleware->dispatch($request, $response);

Options

__construct(bool $displayDetails = true, bool $logErrors = true)

The error handler includes detailed information on error diagnostics and saving to a log file. To enable this you need to set the displayDetails and logErrors setting to true.

setLogger(LoggerInterface $logger)

You must set a PSR logger if logErrors is set to true.

setRenderer(ErrorRendererInterface $renderer = null, Throwable $exception)

You can set up a custom renderer for printing errors.

use Embryo\Error\Interfaces\ErrorRendererInterface;
use Psr\Http\Message\{ServerRequestInterface, ResponseInterface};

class CustomRenderer implements ErrorRendererInterface 
{
    public function render(ServerRequestInterface $request, ResponseInterface $response, \Throwable $exception): ResponseInterface
    {
        // custom logic...
        return $response;
    }
}

$errorHandler = (new ErrorHandler)->setRenderer(CustomRenderer::class);