Skip to content

Error Handler Package

Error and exception handling with debug/production modes.

Installation

bash
composer require lighthouse/error-handler

Basic Usage

php
use Lighthouse\ErrorHandler\ErrorHandler;
use Lighthouse\Http\Response;

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

try {
    // ... application code
} catch (Throwable $e) {
    $response = $errorHandler->handle($e, $request);
}

HTTP Exceptions

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

throw new NotFoundException('User not found');           // 404
throw new BadRequestException('Invalid input');          // 400
throw new UnauthorizedException('Please log in');        // 401
throw new ForbiddenException('Access denied');           // 403
throw new MethodNotAllowedException(['GET', 'POST']);    // 405
throw new HttpException('Custom error', 418);            // Custom

Debug vs Production

Debug mode (development):

php
$errorHandler = new ErrorHandler(debug: true, ...);

Shows:

  • Exception class and message
  • File and line number
  • Full stack trace
  • Request information

Production mode:

php
$errorHandler = new ErrorHandler(debug: false, ...);

Shows:

  • Clean error page
  • Generic messages
  • No sensitive info

PSR-15 Middleware

php
use Lighthouse\ErrorHandler\ErrorMiddleware;

$middleware = new ErrorMiddleware($errorHandler);

// With logging
$middleware = new ErrorMiddleware(
    $errorHandler,
    function (Throwable $e, $request) use ($logger) {
        $logger->error($e->getMessage());
    }
);

JSON Responses

Automatic JSON for Accept: application/json:

json
{
    "error": {
        "status": 404,
        "message": "User not found"
    }
}

Custom Renderers

php
use Lighthouse\ErrorHandler\Renderer\RendererInterface;

class XmlRenderer implements RendererInterface
{
    public function render(Throwable $e, $request): string
    {
        return "<error>{$e->getMessage()}</error>";
    }
}

$errorHandler->registerRenderer('application/xml', new XmlRenderer());

Custom Headers

php
throw new HttpException('Rate limited', 429, [
    'Retry-After' => '60',
    'X-RateLimit-Remaining' => '0',
]);

Toggle Debug Mode

php
$errorHandler->setDebug(false);
$errorHandler->isDebug(); // false

Released under the MIT License.