PHPackages                             middlewares/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. [HTTP &amp; Networking](/categories/http)
4. /
5. middlewares/error-handler

ActiveLibrary[HTTP &amp; Networking](/categories/http)

middlewares/error-handler
=========================

Middleware to handle http errors

v3.1.0(1y ago)14110.9k↑16.5%6[1 issues](https://github.com/middlewares/error-handler/issues)[1 PRs](https://github.com/middlewares/error-handler/pulls)11MITPHPPHP ^7.2 || ^8.0CI failing

Since Oct 3Pushed 1y ago2 watchersCompare

[ Source](https://github.com/middlewares/error-handler)[ Packagist](https://packagist.org/packages/middlewares/error-handler)[ Docs](https://github.com/middlewares/error-handler)[ RSS](/packages/middlewares-error-handler/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (10)Dependencies (8)Versions (19)Used By (11)

middlewares/error-handler
=========================

[](#middlewareserror-handler)

[![Latest Version on Packagist](https://camo.githubusercontent.com/b09c2cc85690aba3ae466e6351546422d1b53e3d17eaa6262395a6e56a844e80/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6964646c6577617265732f6572726f722d68616e646c65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/middlewares/error-handler)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Testing](https://github.com/middlewares/error-handler/workflows/testing/badge.svg)](https://github.com/middlewares/error-handler/workflows/testing/badge.svg)[![Total Downloads](https://camo.githubusercontent.com/c0dec5013cf461fb051d81cc49bde445ac75943d06337986ea5295d9384f5371/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d6964646c6577617265732f6572726f722d68616e646c65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/middlewares/error-handler)

Middleware to catch and format errors encountered while handling the request.

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

[](#requirements)

- PHP &gt;= 7.2
- A [PSR-7 http library](https://github.com/middlewares/awesome-psr15-middlewares#psr-7-implementations)
- A [PSR-15 middleware dispatcher](https://github.com/middlewares/awesome-psr15-middlewares#dispatcher)

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

[](#installation)

This package is installable and autoloadable via Composer as [middlewares/error-handler](https://packagist.org/packages/middlewares/error-handler).

```
composer require middlewares/error-handler
```

Example
-------

[](#example)

```
use Middlewares\ErrorFormatter;
use Middlewares\ErrorHandler;
use Middlewares\Utils\Dispatcher;

// Create a new ErrorHandler instance
// Any number of formatters can be added. One will be picked based on the Accept
// header of the request. If no formatter matches, the first formatter in the array
// will be used.
$errorHandler = new ErrorHandler([
    new ErrorFormatter\HtmlFormatter(),
    new ErrorFormatter\ImageFormatter(),
    new ErrorFormatter\JsonFormatter(),
    new ErrorFormatter\PlainFormatter(),
    new ErrorFormatter\SvgFormatter(),
    new ErrorFormatter\XmlFormatter(),
]);

// ErrorHandler should always be the first middleware in the stack!
$dispatcher = new Dispatcher([
    $errorHandler,
    // ...
    function ($request) {
        throw HttpErrorException::create(404);
    }
]);

$request = $serverRequestFactory->createServerRequest('GET', '/');
$response = $dispatcher->dispatch($request);
```

Usage
-----

[](#usage)

Add the [formatters](src/ErrorFormatter) to be used (instances of `Middlewares\ErrorFormatter\FormatterInterface`). If no formatters are provided, use all available.

```
$errorHandler = new ErrorHandler([
    new ErrorFormatter\HtmlFormatter(),
    new ErrorFormatter\JsonFormatter()
]);
```

**Note:** If no formatter is found, the first value of the array will be used. In the example above, `HtmlFormatter`.

### How to log the error and delegate the formatting to the middleware

[](#how-to-log-the-error-and-delegate-the-formatting-to-the-middleware)

Please note that the following snippet must go even before error-hander's middleware, which usually goes first.

```
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
    try {
        return $handler->handle($request);
    } catch (Throwable $exception) {
        $this->logger->critical('Uncaught {error}', [
            'error' => $exception->getMessage(),
            'exception' => $exception, // If you use Monolog, this is correct
        ]);

        // leave it for the middleware
        throw $exception;
    }
}
```

### How to use a custom response for Production

[](#how-to-use-a-custom-response-for-production)

This snippet might come handy when you want to customize your response in production.

```
class PrettyPage implements StreamFactoryInterface
{
    public function createStream(string $content = ''): StreamInterface
    {
        return Factory::createStream('Pretty page');
    }

    public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface
    {
        // This is safe as the Middleware only uses createStream()
        throw new Exception('Not implemented');
    }

    public function createStreamFromResource($resource): StreamInterface
    {
        // This is safe as the Middleware only uses createStream()
        throw new Exception('Not implemented');
    }
}

$errorHandler = new ErrorHandler([
    new HtmlFormatter(
        null,
        new PrettyPage,
    ),
]);
```

---

Please see [CHANGELOG](CHANGELOG.md) for more information about recent changes and [CONTRIBUTING](CONTRIBUTING.md) for contributing details.

The MIT License (MIT). Please see [LICENSE](LICENSE) for more information.

###  Health Score

50

—

FairBetter than 95% of packages

Maintenance42

Moderate activity, may be stable

Popularity41

Moderate usage in the ecosystem

Community28

Small or concentrated contributor base

Maturity77

Established project with proven stability

 Bus Factor1

Top contributor holds 81.5% 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

Every ~193 days

Recently: every ~535 days

Total

17

Last Release

468d ago

Major Versions

v0.9.0 → v1.0.02018-01-26

v1.2.0 → v2.0.02019-05-10

v2.0.0 → v3.0.02019-11-30

PHP version history (4 changes)v0.1.0PHP ^5.6 || ^7.0

v0.8.0PHP ^7.0

v3.0.0PHP ^7.2

v3.0.1PHP ^7.2 || ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/e99df56b617f4af8cf0556a51a0ca20c7420104920c57d7e9eab093f92bb744f?d=identicon)[oscarotero](/maintainers/oscarotero)

![](https://www.gravatar.com/avatar/42e0d72f42eb7d84f67e20d28606da42e5a3248ca908b1eadb4366aafeae2561?d=identicon)[filisko](/maintainers/filisko)

---

Top Contributors

[![oscarotero](https://avatars.githubusercontent.com/u/377873?v=4)](https://github.com/oscarotero "oscarotero (75 commits)")[![filisko](https://avatars.githubusercontent.com/u/8798694?v=4)](https://github.com/filisko "filisko (12 commits)")[![shadowhand](https://avatars.githubusercontent.com/u/38203?v=4)](https://github.com/shadowhand "shadowhand (2 commits)")[![jakejohns](https://avatars.githubusercontent.com/u/174708?v=4)](https://github.com/jakejohns "jakejohns (1 commits)")[![rolfvandekrol](https://avatars.githubusercontent.com/u/434397?v=4)](https://github.com/rolfvandekrol "rolfvandekrol (1 commits)")[![tomkyle](https://avatars.githubusercontent.com/u/412560?v=4)](https://github.com/tomkyle "tomkyle (1 commits)")

---

Tags

errorhttpmiddlewarepsr-15httppsr-7formattermiddlewareserverexceptionerrorhandlerpsr-15

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[middlewares/request-handler

Middleware to execute request handlers

451.8M30](/packages/middlewares-request-handler)[mezzio/mezzio

PSR-15 Middleware Microframework

3923.8M125](/packages/mezzio-mezzio)[middlewares/whoops

Middleware to use Whoops as error handler

34211.0k27](/packages/middlewares-whoops)[middlewares/fast-route

Middleware to use FastRoute

98205.1k15](/packages/middlewares-fast-route)[middlewares/negotiation

Middleware to implement content negotiation

46458.6k11](/packages/middlewares-negotiation)[middlewares/payload

Middleware to parse the body of the request with support for json, csv and url-encode

33472.0k17](/packages/middlewares-payload)

PHPackages © 2026

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