PHP code example of davidecesarano / embryo-error

1. Go to this page and download the library: Download davidecesarano/embryo-error 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/ */

    

davidecesarano / embryo-error example snippets


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

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