PHPackages                             lighthouse/error-handler - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Debugging &amp; Profiling](/categories/debugging)
4. /
5. lighthouse/error-handler

ActiveLibrary[Debugging &amp; Profiling](/categories/debugging)

lighthouse/error-handler
========================

Error and Exception Handler for the Lighthouse framework

v0.1.0(6mo ago)0111MITPHPPHP ^8.2CI failing

Since Dec 17Pushed 6mo agoCompare

[ Source](https://github.com/RichardTrujilloTorres/error-handler)[ Packagist](https://packagist.org/packages/lighthouse/error-handler)[ RSS](/packages/lighthouse-error-handler/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (7)Versions (2)Used By (1)

Lighthouse Error Handler
========================

[](#lighthouse-error-handler)

Error and Exception Handler for the Lighthouse framework.

Installation
------------

[](#installation)

```
composer require lighthouse/error-handler
```

Requirements
------------

[](#requirements)

- PHP 8.2 or higher

Features
--------

[](#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
-----------

[](#quick-start)

### Basic Usage

[](#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

[](#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

[](#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

[](#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-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

[](#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

[](#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(
            '%s',
            htmlspecialchars($exception->getMessage())
        );
    }
}

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

API Reference
-------------

[](#api-reference)

### ErrorHandler

[](#errorhandler)

MethodDescription`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

[](#http-exceptions-1)

ExceptionStatus Code`BadRequestException`400`UnauthorizedException`401`ForbiddenException`403`NotFoundException`404`MethodNotAllowedException`405`HttpException`Custom### ErrorMiddleware

[](#errormiddleware)

MethodDescription`process(ServerRequestInterface, RequestHandlerInterface)`PSR-15 middleware`setErrorLogger(callable)`Set error logging callbackTesting
-------

[](#testing)

```
composer test
```

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for details.

Part of the Lighthouse Framework
--------------------------------

[](#part-of-the-lighthouse-framework)

This package is part of the [Lighthouse Framework](https://github.com/lighthouse-php), an educational PHP framework designed to teach how modern frameworks work internally.

###  Health Score

30

—

LowBetter than 62% of packages

Maintenance66

Regular maintenance activity

Popularity5

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

198d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/13813941?v=4)[Richard Trujillo](/maintainers/richardtrujillotorres)[@RichardTrujilloTorres](https://github.com/RichardTrujilloTorres)

---

Top Contributors

[![RichardTrujilloTorres](https://avatars.githubusercontent.com/u/13813941?v=4)](https://github.com/RichardTrujilloTorres "RichardTrujilloTorres (1 commits)")

---

Tags

debugexceptionerrorwhoopshandlerlighthouse

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/lighthouse-error-handler/health.svg)

```
[![Health](https://phpackages.com/badges/lighthouse-error-handler/health.svg)](https://phpackages.com/packages/lighthouse-error-handler)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.9k19.5M1.8k](/packages/cakephp-cakephp)[typo3/cms

TYPO3 CMS is a free open source Content Management Framework initially created by Kasper Skaarhoj and licensed under GNU/GPL.

1.2k1.9M122](/packages/typo3-cms)[cakephp/authentication

Authentication plugin for CakePHP

1214.1M106](/packages/cakephp-authentication)[typo3/cms-core

TYPO3 CMS Core

3713.2M5.1k](/packages/typo3-cms-core)[typo3/cms-adminpanel

TYPO3 CMS Admin Panel - The Admin Panel displays information about your site in the frontend and contains a range of metrics including debug and caching information.

115.7M66](/packages/typo3-cms-adminpanel)[flarum/core

Delightfully simple forum software.

201.4M2.3k](/packages/flarum-core)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
