PHPackages                             meritum/http-exception-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. meritum/http-exception-handler

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

meritum/http-exception-handler
==============================

meritum/http exception handler that translates exceptions into structured JSON error responses using the meritum/structured-logging pipeline

1.1.0(1mo ago)038MITPHPPHP ^8.4CI passing

Since Jun 12Pushed 1mo agoCompare

[ Source](https://github.com/MeritumIO/http-exception-handler)[ Packagist](https://packagist.org/packages/meritum/http-exception-handler)[ RSS](/packages/meritum-http-exception-handler/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (14)Versions (3)Used By (0)

meritum/http-exception-handler
==============================

[](#meritumhttp-exception-handler)

HTTP exception handler that translates exceptions into structured JSON error responses using the `meritum/structured-logging` pipeline.

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

[](#requirements)

- PHP 8.4+
- `georgeff/kernel` ^1.6
- `meritum/http` ^1.0
- `meritum/structured-logging` ^1.0

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

[](#installation)

```
composer require meritum/http-exception-handler
```

Usage
-----

[](#usage)

### Module registration

[](#module-registration)

Register `ExceptionHandlerModule` alongside `StructuredLoggingModule`. `StructuredLoggingModule` requires a `LoggerInterface` to already be registered:

```
use Meritum\HttpExceptionHandler\ExceptionHandlerModule;
use Meritum\StructuredLogging\StructuredLoggingModule;

$kernel->define(LoggerInterface::class, fn() => new MyLogger());
$kernel->addModule(new StructuredLoggingModule());
$kernel->addModule(new ExceptionHandlerModule());
$kernel->boot();
```

`ExceptionHandlerModule` registers:

- `ExceptionHandlerInterface` — the handler `meritum/http` resolves when an exception reaches the kernel boundary
- `HttpExceptionTranslationHandler` — tagged as `exception.translator.handlers`, translates `HttpExceptionInterface` instances into structured domain exceptions

### How it works

[](#how-it-works)

When an exception reaches the HTTP kernel boundary:

1. `ExceptionHandlerInterface::handle()` is called with the exception and the current request
2. The exception is passed through the `meritum/structured-logging` translate→report pipeline — it is translated to a domain exception and logged
3. An `ErrorEnvelope` is built from the domain exception and returned as a JSON response

HTTP exceptions (implementing `HttpExceptionInterface`) are translated by `HttpExceptionTranslationHandler` into an `HttpDomainException`, which carries the request context and sets the appropriate log severity. Any other exception falls through to the structured-logging catch-all translator and produces a generic 500 response.

### Response format

[](#response-format)

All error responses use a consistent JSON envelope:

```
{
  "code":   "HTTP_404",
  "status": 404,
  "title":  "Not Found",
  "detail": "The requested resource could not be found."
}
```

- `code` — the domain exception error code; `HTTP_` followed by the HTTP status code for HTTP exceptions
- `status` — the HTTP status code as an integer; also set as the response status
- `title` — the HTTP exception title; `"Unexpected Error"` for non-HTTP exceptions
- `detail` — the exception message; may be `null`
- `errors` — an optional array of additional error detail objects; omitted when empty

### Custom HTTP exceptions

[](#custom-http-exceptions)

Extend `HttpException` or implement `HttpExceptionInterface` directly to define domain-specific HTTP exceptions:

```
use Meritum\Http\Exception\HttpException;

final class ResourceNotFoundException extends HttpException
{
    protected string $title = 'Not Found';
    protected int $status = 404;
}
```

Throw the exception from within the request pipeline:

```
throw new ResourceNotFoundException($request, 'User 42 does not exist.');
```

`HttpExceptionTranslationHandler` matches any `HttpExceptionInterface`, so custom exceptions are handled automatically with no additional registration.

### Custom translation handlers

[](#custom-translation-handlers)

To produce a different domain exception for a specific HTTP exception type, implement `TranslationHandler` and register it at a higher priority than the default handler (`0`):

```
use Throwable;
use Meritum\StructuredLogging\TranslationHandler;
use Meritum\StructuredLogging\Exception\DomainException;

final class ValidationExceptionTranslationHandler implements TranslationHandler
{
    public function matches(Throwable $exception): bool
    {
        return $exception instanceof ValidationHttpException;
    }

    public function handle(Throwable $exception): DomainException
    {
        assert($exception instanceof ValidationHttpException);

        return new ValidationDomainException($exception);
    }

    public function priority(): int
    {
        return 1;
    }
}
```

Register and tag it in your module:

```
$kernel->define(ValidationExceptionTranslationHandler::class, fn() => new ValidationExceptionTranslationHandler())
       ->tag('exception.translator.handlers');
```

Because this handler runs at priority `1`, it matches before `HttpExceptionTranslationHandler` (`0`) for `ValidationHttpException` instances. All other HTTP exceptions continue to be handled by the default.

### Using `ErrorEnvelope` directly

[](#using-errorenvelope-directly)

`ErrorEnvelope` is public API. Use it to build consistent error responses anywhere in your application:

```
use Meritum\HttpExceptionHandler\ErrorEnvelope;

// From a caught domain exception
$envelope = ErrorEnvelope::fromDomainException($domainException);

// With explicit values
$envelope = new ErrorEnvelope('HTTP_403', 403, 'Forbidden', 'You do not have permission.');

return new JsonResponse($envelope, $envelope->status);
```

### Attaching additional errors

[](#attaching-additional-errors)

Call `withErrors()` to attach a list of error detail objects to the envelope. The shape of each entry is up to the caller — `withErrors()` carries any `string`-keyed map:

```
$envelope = ErrorEnvelope::fromDomainException($domainException)
    ->withErrors([
        ['field' => 'email', 'message' => 'Must be a valid email address.'],
        ['field' => 'age',   'message' => 'Must be an integer greater than 0.'],
    ]);

return new JsonResponse($envelope, $envelope->status);
```

This produces:

```
{
  "code":   "HTTP_422",
  "status": 422,
  "title":  "Unprocessable Entity",
  "detail": "The request body contains validation errors.",
  "errors": [
    { "field": "email", "message": "Must be a valid email address." },
    { "field": "age",   "message": "Must be an integer greater than 0." }
  ]
}
```

`errors` is omitted from the response entirely when `withErrors()` is not called. `withErrors()` replaces any previously set errors — pass the full list in a single call.

License
-------

[](#license)

MIT

###  Health Score

43

—

FairBetter than 89% of packages

Maintenance92

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity52

Maturing project, gaining track record

 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

Every ~7 days

Total

2

Last Release

38d ago

### Community

Maintainers

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

---

Top Contributors

[![MikeGeorgeff](https://avatars.githubusercontent.com/u/6169468?v=4)](https://github.com/MikeGeorgeff "MikeGeorgeff (2 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/meritum-http-exception-handler/health.svg)

```
[![Health](https://phpackages.com/badges/meritum-http-exception-handler/health.svg)](https://phpackages.com/packages/meritum-http-exception-handler)
```

###  Alternatives

[php-http/cache-plugin

PSR-6 Cache plugin for HTTPlug

25026.1M82](/packages/php-http-cache-plugin)[httpsoft/http-message

Strict and fast implementation of PSR-7 and PSR-17

87965.9k124](/packages/httpsoft-http-message)[serpapi/google-search-results-php

Get Google, Bing, Baidu, Ebay, Yahoo, Yandex, Home depot, Naver, Apple, Duckduckgo, Youtube search results via SerpApi.com

69127.2k](/packages/serpapi-google-search-results-php)[thesis/nats

Async (fiber based) client for Nats.

754.4k](/packages/thesis-nats)[jasny/http-signature

Implementation of the IETF HTTP Signatures draft RFC

10104.7k](/packages/jasny-http-signature)

PHPackages © 2026

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