PHPackages                             ctw/ctw-middleware-httpexception - 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. ctw/ctw-middleware-httpexception

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

ctw/ctw-middleware-httpexception
================================

This PSR-15 middleware catches exceptions implementing "Ctw\\Http\\HttpException\\HttpException\\HttpExceptionInterface" and returns a custom error page.

4.0.5(5mo ago)1134BSD-3-ClausePHPPHP ^8.3CI passing

Since Mar 14Pushed 5mo ago1 watchersCompare

[ Source](https://github.com/jonathanmaron/ctw-middleware-httpexception)[ Packagist](https://packagist.org/packages/ctw/ctw-middleware-httpexception)[ RSS](/packages/ctw-ctw-middleware-httpexception/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (10)Versions (43)Used By (0)

Package "ctw/ctw-middleware-httpexception"
==========================================

[](#package-ctwctw-middleware-httpexception)

[![Latest Stable Version](https://camo.githubusercontent.com/aeced45afb13545f2e7406c16f9f62b119141348a1c8110e3a9835ec2fcd9082/68747470733a2f2f706f7365722e707567782e6f72672f6374772f6374772d6d6964646c65776172652d68747470657863657074696f6e2f762f737461626c65)](https://packagist.org/packages/ctw/ctw-middleware-httpexception)[![GitHub Actions](https://github.com/jonathanmaron/ctw-middleware-httpexception/actions/workflows/tests.yml/badge.svg)](https://github.com/jonathanmaron/ctw-middleware-httpexception/actions/workflows/tests.yml)[![Scrutinizer Build](https://camo.githubusercontent.com/1b33ce1e487ac7a241bf22f99ff717959724464399069b0d583a4e5805d31f50/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d6d6964646c65776172652d68747470657863657074696f6e2f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-middleware-httpexception/build-status/master)[![Scrutinizer Quality](https://camo.githubusercontent.com/c37ba99bd593d23839daf9cc354be7842326cbfb93a07d69f9b80e7dd2b07304/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d6d6964646c65776172652d68747470657863657074696f6e2f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-middleware-httpexception/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/44d747162ebcea71eadc377994e0fd1c148815d3395162ab43c6e924d3b055b5/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a6f6e617468616e6d61726f6e2f6374772d6d6964646c65776172652d68747470657863657074696f6e2f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jonathanmaron/ctw-middleware-httpexception/?branch=master)

PSR-15 middleware that catches HTTP exceptions and renders custom error pages for production environments, with automatic JSON support for API requests.

Introduction
------------

[](#introduction)

### Why This Library Exists

[](#why-this-library-exists)

Web applications need graceful error handling that presents user-friendly error pages in production while preserving detailed error information during development. The default PHP error handling exposes sensitive information and provides poor user experience.

This middleware integrates with `ctw/ctw-http` exceptions to:

- **Catch HTTP exceptions**: Intercepts exceptions implementing `HttpExceptionInterface`
- **Render custom templates**: Uses Mezzio's template renderer for branded error pages
- **Support JSON responses**: Automatically returns RFC 7807 Problem Details for API requests
- **Respect development mode**: Re-throws exceptions in development for debugging

### Problems This Library Solves

[](#problems-this-library-solves)

1. **Generic error pages**: Default framework error pages are ugly and expose technical details
2. **Missing JSON errors**: API clients receive HTML error pages instead of structured JSON
3. **Development vs production**: Need different error handling behavior per environment
4. **Inconsistent responses**: Different error codes handled inconsistently across the application
5. **Security exposure**: Stack traces and internal paths leak in production errors

### Where to Use This Library

[](#where-to-use-this-library)

- **Production web applications**: Present branded, user-friendly error pages
- **REST APIs**: Return RFC 7807 Problem Details JSON for all HTTP errors
- **Hybrid applications**: Automatically serve HTML or JSON based on `Accept` header
- **Mezzio applications**: Integrates seamlessly with the Mezzio template system
- **Multi-environment deployments**: Different behavior in development vs production

### Design Goals

[](#design-goals)

1. **Content negotiation**: Serves HTML or JSON based on client `Accept` header
2. **RFC 7807 compliance**: JSON errors follow Problem Details specification
3. **Template-based rendering**: Uses Mezzio template renderer for HTML responses
4. **Development awareness**: Re-throws exceptions when development mode is enabled
5. **Exception hierarchy**: Only catches `HttpExceptionInterface`, re-throws others

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

[](#requirements)

- PHP 8.3 or higher
- ctw/ctw-middleware ^4.0
- ctw/ctw-http ^4.0
- mezzio/mezzio-template ^2.4
- mezzio/mezzio-laminasviewrenderer ^2.2

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

[](#installation)

Install by adding the package as a [Composer](https://getcomposer.org) requirement:

```
composer require ctw/ctw-middleware-httpexception
```

Usage Examples
--------------

[](#usage-examples)

### Basic Pipeline Registration (Mezzio)

[](#basic-pipeline-registration-mezzio)

```
use Ctw\Middleware\HttpExceptionMiddleware\HttpExceptionMiddleware;

// In config/pipeline.php - place early in the pipeline
$app->pipe(HttpExceptionMiddleware::class);
```

### ConfigProvider Registration

[](#configprovider-registration)

```
// config/config.php
return [
    // ...
    \Ctw\Middleware\HttpExceptionMiddleware\ConfigProvider::class,
];
```

### Throwing HTTP Exceptions

[](#throwing-http-exceptions)

```
use Ctw\Http\HttpException;

// In a handler or middleware
throw new HttpException\NotFoundException('Page not found');
throw new HttpException\ForbiddenException('Access denied');
throw new HttpException\InternalServerErrorException('Something went wrong');
```

### HTML Response (Browser)

[](#html-response-browser)

When a browser requests a page and an exception occurs:

```
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=UTF-8

404 Not Found

  Not Found
  The requested resource could not be found.

```

### JSON Response (API)

[](#json-response-api)

When a client sends `Accept: application/json`:

```
HTTP/1.1 404 Not Found
Content-Type: application/problem+json

{
  "type": "https://httpstatuses.com/404",
  "title": "Not Found",
  "status": 404,
  "detail": "Page not found"
}
```

### Configuration Options

[](#configuration-options)

```
// config/autoload/error-handler.global.php
return [
    'error_handler' => [
        'template_http_exception' => 'error::http-exception',
        'layout' => 'layout::default',
    ],
];
```

OptionDescriptionDefault`template_http_exception`Template name for HTML error pages`error::http-exception.phtml``layout`Layout template for error pages(none)### Template Variables

[](#template-variables)

The error template receives:

VariableTypeDescription`entity``HttpStatus`HTTP status entity with code, name, phrase`exception``HttpExceptionInterface`The caught exception`layout``string`Layout template name (if configured)### Development Mode

[](#development-mode)

In development mode (when `laminas/laminas-development-mode` is enabled), exceptions are re-thrown to allow the Whoops error handler or similar tools to display detailed debugging information.

###  Health Score

47

—

FairBetter than 93% of packages

Maintenance76

Regular maintenance activity

Popularity12

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity79

Established project with proven stability

 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 ~42 days

Total

42

Last Release

165d ago

Major Versions

0.0.2 → 1.0.02021-03-14

1.0.5 → 2.0.02022-02-14

2.0.1 → 3.0.02022-07-07

3.0.25 → 4.0.02024-06-18

PHP version history (5 changes)0.0.1PHP ^7.4 || ^8.0

1.0.1PHP ^7.4

3.0.0PHP ^8.0

3.0.9PHP ^8.1

4.0.0PHP ^8.3

### Community

Maintainers

![](https://www.gravatar.com/avatar/18d8bc9bdee8ab1b0cfccce6a06d2438acbed3a58b0046c4834c5678f6769342?d=identicon)[jonathanmaron](/maintainers/jonathanmaron)

---

Top Contributors

[![jonathanmaron](https://avatars.githubusercontent.com/u/298462?v=4)](https://github.com/jonathanmaron "jonathanmaron (67 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/ctw-ctw-middleware-httpexception/health.svg)

```
[![Health](https://phpackages.com/badges/ctw-ctw-middleware-httpexception/health.svg)](https://phpackages.com/packages/ctw-ctw-middleware-httpexception)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[mezzio/mezzio

PSR-15 Middleware Microframework

3883.6M96](/packages/mezzio-mezzio)[laminas/laminas-psr7bridge

Bidirectional conversions between PSR-7 and laminas-http messages

117.9M18](/packages/laminas-laminas-psr7bridge)[mezzio/mezzio-authentication-oauth2

OAuth2 (server) authentication middleware for Mezzio and PSR-7 applications.

28483.0k2](/packages/mezzio-mezzio-authentication-oauth2)[mimmi20/browser-detector

Library to detect Browsers and Devices

48153.5k3](/packages/mimmi20-browser-detector)[mezzio/mezzio-swoole

Swoole support for Mezzio

92238.9k3](/packages/mezzio-mezzio-swoole)

PHPackages © 2026

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