PHP code example of lighthouse / error-handler

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

    

lighthouse / error-handler example snippets


use Lighthouse\ErrorHandler\ErrorHandler;
use Lighthouse\ErrorHandler\Exception\NotFoundException;

// Create handler with response factory
$errorHandler = new ErrorHandler(
    debug: true, // Set to false in production
    responseFactory: fn(int $status) => new Response($status)
);

// Handle an exception
try {
    throw new NotFoundException('Page not found');
} catch (Throwable $e) {
    $response = $errorHandler->handle($e, $request);
}

use Lighthouse\ErrorHandler\Exception\NotFoundException;
use Lighthouse\ErrorHandler\Exception\BadRequestException;
use Lighthouse\ErrorHandler\Exception\UnauthorizedException;
use Lighthouse\ErrorHandler\Exception\ForbiddenException;
use Lighthouse\ErrorHandler\Exception\MethodNotAllowedException;
use Lighthouse\ErrorHandler\Exception\HttpException;

// 404 Not Found
throw new NotFoundException('User not found');

// 400 Bad Request
throw new BadRequestException('Invalid email format');

// 401 Unauthorized
throw new UnauthorizedException('Please log in');

// 403 Forbidden
throw new ForbiddenException('Access denied');

// 405 Method Not Allowed
throw new MethodNotAllowedException(['GET', 'POST']);

// Custom status code
throw new HttpException('I am a teapot', 418);

use Lighthouse\ErrorHandler\ErrorHandler;
use Lighthouse\ErrorHandler\ErrorMiddleware;

$errorHandler = new ErrorHandler(
    debug: getenv('APP_DEBUG') === 'true',
    responseFactory: fn(int $status) => new Response($status)
);

// Create middleware
$errorMiddleware = new ErrorMiddleware($errorHandler);

// Add to pipeline (should be first)
$pipeline->pipe($errorMiddleware);
$pipeline->pipe($routingMiddleware);
$pipeline->pipe($dispatchMiddleware);

$errorMiddleware = new ErrorMiddleware(
    $errorHandler,
    function (Throwable $e, ServerRequestInterface $request) use ($logger) {
        $logger->error($e->getMessage(), [
            'exception' => $e,
            'uri' => (string) $request->getUri(),
        ]);
    }
);

// Toggle debug mode
$errorHandler->setDebug(false);

use Lighthouse\ErrorHandler\Renderer\RendererInterface;

class XmlRenderer implements RendererInterface
{
    public function render(Throwable $exception, ServerRequestInterface $request): string
    {
        return sprintf(
            '<?xml version="1.0"