PHP code example of componenta / error-handler

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

    

componenta / error-handler example snippets


use Componenta\Error\Handler\HttpErrorHandler;
use Componenta\Error\Http\HttpErrorResponseGenerator;
use Componenta\Error\Http\Middleware\ErrorHandlerMiddleware;
use Psr\Http\Message\ResponseFactoryInterface;

/** @var ResponseFactoryInterface $responseFactory */
$fallback = new HttpErrorResponseGenerator($responseFactory);
$handler = new HttpErrorHandler($fallback);

$middleware = new ErrorHandlerMiddleware($handler);
$response = $middleware->process($request, $next);

$handler->addGenerator(new NotFoundGenerator($responseFactory), priority: 100);
$handler->addGenerator(new ValidationGenerator($responseFactory), priority: 50);

use Componenta\Error\Context\HttpErrorContextInterface;
use Componenta\Error\ErrorContextInterface;
use Componenta\Error\Http\HttpErrorResponseGeneratorInterface;
use InvalidArgumentException;
use Psr\Http\Message\ResponseInterface;
use Throwable;

final readonly class ValidationErrorResponseGenerator implements HttpErrorResponseGeneratorInterface
{
    public function supports(Throwable $exception, ErrorContextInterface $context): bool
    {
        return $context instanceof HttpErrorContextInterface
            && $exception instanceof InvalidArgumentException;
    }

    public function generate(Throwable $exception, HttpErrorContextInterface $context): ResponseInterface
    {
        // Build and return a PSR-7 response.
    }
}

use Componenta\Error\Context\CliContext;
use Componenta\Error\Handler\CliErrorHandler;
use Componenta\Error\Handler\RenderingCliErrorHandler;

$handler = new CliErrorHandler(new RenderingCliErrorHandler());

try {
    $app->run();
} catch (Throwable $exception) {
    $handler->handle($exception, CliContext::fromArgv());
    exit(1);
}

$context = $context->withAttribute('user_id', 123);
$userId = $context->getAttribute('user_id');

$context = HttpContext::fromGlobals($serverRequestCreator);

use Componenta\Error\Event\ErrorEventInterface;
use Componenta\Error\Event\ErrorListener;

$handler->addListener(
    ErrorListener::createFrom(static function (ErrorEventInterface $event): void {
        // log or report $event->exception and $event->context
    }),
    priority: 100,
);