lighthouse / error-handler
Error and Exception Handler for the Lighthouse framework
Installs: 11
Dependents: 1
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/lighthouse/error-handler
Requires
- php: ^8.2
- psr/http-message: ^2.0
- psr/http-server-handler: ^1.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- lighthouse/http: @dev
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^11.0
README
Error and Exception Handler for the Lighthouse framework.
Installation
composer require lighthouse/error-handler
Requirements
- PHP 8.2 or higher
Features
- Debug and production error pages
- HTTP exception classes (404, 401, 403, 405, etc.)
- HTML and JSON error renderers
- PSR-15 error middleware
- Custom renderer support
- Error logging integration
Quick Start
Basic Usage
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); }
HTTP Exceptions
Throw HTTP-specific exceptions:
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);
PSR-15 Middleware
Use as middleware in your pipeline:
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);
Error Logging
Add an error logger:
$errorMiddleware = new ErrorMiddleware( $errorHandler, function (Throwable $e, ServerRequestInterface $request) use ($logger) { $logger->error($e->getMessage(), [ 'exception' => $e, 'uri' => (string) $request->getUri(), ]); } );
Debug vs Production Mode
Debug mode (development):
- Detailed error page with stack trace
- Exception class name and file location
- Request information
Production mode:
- Clean, user-friendly error page
- Generic error messages for 500 errors
- No sensitive information exposed
// Toggle debug mode $errorHandler->setDebug(false);
JSON Responses
The handler automatically detects Accept: application/json and returns JSON:
{
"error": {
"status": 404,
"message": "User not found"
}
}
In debug mode:
{
"error": {
"status": 404,
"message": "User not found",
"type": "Lighthouse\\ErrorHandler\\Exception\\NotFoundException",
"file": "/app/src/UserController.php",
"line": 42,
"trace": [...]
}
}
Custom Renderers
Create custom error renderers:
use Lighthouse\ErrorHandler\Renderer\RendererInterface; class XmlRenderer implements RendererInterface { public function render(Throwable $exception, ServerRequestInterface $request): string { return sprintf( '<?xml version="1.0"?><error><message>%s</message></error>', htmlspecialchars($exception->getMessage()) ); } } $errorHandler->registerRenderer('application/xml', new XmlRenderer());
API Reference
ErrorHandler
| Method | Description |
|---|---|
handle(Throwable, ServerRequestInterface) |
Handle exception and return response |
registerRenderer(string $contentType, RendererInterface) |
Register custom renderer |
setDefaultRenderer(RendererInterface) |
Set default renderer |
isDebug() |
Check if debug mode is enabled |
setDebug(bool) |
Set debug mode |
HTTP Exceptions
| Exception | Status Code |
|---|---|
BadRequestException |
400 |
UnauthorizedException |
401 |
ForbiddenException |
403 |
NotFoundException |
404 |
MethodNotAllowedException |
405 |
HttpException |
Custom |
ErrorMiddleware
| Method | Description |
|---|---|
process(ServerRequestInterface, RequestHandlerInterface) |
PSR-15 middleware |
setErrorLogger(callable) |
Set error logging callback |
Testing
composer test
License
MIT License. See LICENSE for details.
Part of the Lighthouse Framework
This package is part of the Lighthouse Framework, an educational PHP framework designed to teach how modern frameworks work internally.