Skip to content

davidecesarano/Embryo-Error

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Embryo Error

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);