PHPackages                             andrewdyer/json-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. [Utility &amp; Helpers](/categories/utility)
4. /
5. andrewdyer/json-error-handler

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

andrewdyer/json-error-handler
=============================

A structured JSON error handler for Slim Framework applications that maps exceptions to typed, consistent error payloads

0.2.6(1w ago)082MITPHPPHP ^8.3

Since Apr 15Pushed 1w agoCompare

[ Source](https://github.com/andrewdyer/json-error-handler)[ Packagist](https://packagist.org/packages/andrewdyer/json-error-handler)[ Docs](https://github.com/andrewdyer/json-error-handler)[ RSS](/packages/andrewdyer-json-error-handler/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (8)Dependencies (8)Versions (10)Used By (0)

[![JSON Error Handler](https://camo.githubusercontent.com/f4a7619028e2c5780a274f24db1b2ad517e02d160209c893165cbb83e8b4739d/68747470733a2f2f7075626c69632d6173736574732e616e64726577647965722e726f636b732f696d616765732f636f766572732f6a736f6e2d6572726f722d68616e646c65722e706e67)](https://camo.githubusercontent.com/f4a7619028e2c5780a274f24db1b2ad517e02d160209c893165cbb83e8b4739d/68747470733a2f2f7075626c69632d6173736574732e616e64726577647965722e726f636b732f696d616765732f636f766572732f6a736f6e2d6572726f722d68616e646c65722e706e67)

 [![Latest Stable Version](https://camo.githubusercontent.com/6228a5b3d7436d53f2a879a49ae9e4b3f9ccef96156be22d0cf61a969f58abcf/68747470733a2f2f706f7365722e707567782e6f72672f616e64726577647965722f6a736f6e2d6572726f722d68616e646c65722f762f737461626c653f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/andrewdyer/json-error-handler) [![Total Downloads](https://camo.githubusercontent.com/cdbbf4fb9df51289f71cf5b5e772bf96bdaa2c1e6d2e9e32166d0eee181af77a/68747470733a2f2f706f7365722e707567782e6f72672f616e64726577647965722f6a736f6e2d6572726f722d68616e646c65722f646f776e6c6f6164733f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/andrewdyer/json-error-handler) [![License](https://camo.githubusercontent.com/f291f4309f4a3d1a97e20e51b2b3f8ea8f7dd5dc9f0b3371306cbd8c3240d03f/68747470733a2f2f706f7365722e707567782e6f72672f616e64726577647965722f6a736f6e2d6572726f722d68616e646c65722f6c6963656e73653f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/andrewdyer/json-error-handler) [![PHP Version Required](https://camo.githubusercontent.com/7a73e45ce68c72edaa2ab8b73f1388208ba8efc4b6683b5c9bb47cecd8eeb6de/68747470733a2f2f706f7365722e707567782e6f72672f616e64726577647965722f6a736f6e2d6572726f722d68616e646c65722f726571756972652f7068703f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/andrewdyer/json-error-handler)

JSON Error Handler
==================

[](#json-error-handler)

A structured JSON error handler for [Slim Framework](https://www.slimframework.com/) applications that maps exceptions to typed, consistent error payloads.

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

[](#introduction)

This library provides a JSON error handler for Slim applications. It extends Slim's built-in error handling to intercept exceptions and transform them into structured JSON responses, mapping HTTP exceptions to typed error payloads with appropriate status codes. The handler supports optional error detail exposure for debug environments and integrates directly with Slim's error middleware and shutdown handling workflows.

Prerequisites
-------------

[](#prerequisites)

- **[PHP](https://www.php.net/)**: Version 8.3 or higher is required.
- **[Composer](https://getcomposer.org/)**: Dependency management tool for PHP.
- **[Slim Framework](https://www.slimframework.com/)**: Version 4 is required.

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

[](#installation)

```
composer require andrewdyer/json-error-handler
```

Getting Started
---------------

[](#getting-started)

### 1. Create the application

[](#1-create-the-application)

```
use Slim\Factory\AppFactory;

$app = AppFactory::create();
```

### 2. Add error middleware

[](#2-add-error-middleware)

Add the error middleware and set `JsonErrorHandler` as the default handler. The `$displayErrorDetails` flag controls whether exception messages are included in responses — this should be `false` in production:

```
use AndrewDyer\JsonErrorHandler\JsonErrorHandler;

$displayErrorDetails = true;

$errorMiddleware = $app->addErrorMiddleware(
    $displayErrorDetails,
    logErrors: true,
    logErrorDetails: true
);

$errorHandler = new JsonErrorHandler(
    $app->getCallableResolver(),
    $app->getResponseFactory(),
    logger: null
);

$errorMiddleware->setDefaultErrorHandler($errorHandler);
```

> **Note:** A PSR-3 logger can be passed as the third argument to enable error logging. [Monolog](https://github.com/Seldaek/monolog) is a popular choice for this.

By default, payloads are encoded with `JSON_PRETTY_PRINT`. Custom flags can be passed as the fourth constructor argument:

```
$errorHandler = new JsonErrorHandler(
    $app->getCallableResolver(),
    $app->getResponseFactory(),
    logger: null,
    jsonEncodeFlags: JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
```

Note that `JSON_THROW_ON_ERROR` is always masked out internally to prevent encoding failures from cascading during error handling.

### 3. Register routes

[](#3-register-routes)

Register routes to handle incoming requests:

```
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Exception\HttpNotFoundException;

$app->get('/hello', function (Request $request, Response $response): Response {
    $response->getBody()->write(json_encode(['message' => 'Hello, world.']));
    return $response->withHeader('Content-Type', 'application/json');
});

$app->get('/error', function (Request $request, Response $response): Response {
    throw new HttpNotFoundException($request);
});
```

### 4. Run the application

[](#4-run-the-application)

Start the application to begin handling incoming HTTP requests:

```
$app->run();
```

Usage
-----

[](#usage)

Once the handler is registered, Slim will route exceptions through `JsonErrorHandler` and return structured JSON error responses.

### Successful request

[](#successful-request)

```
GET /hello
Accept: application/json

```

**Response: 200 OK**

```
{
  "message": "Hello, world."
}
```

### Error request

[](#error-request)

```
GET /error
Accept: application/json

```

**Response: 404 Not Found**

```
{
  "error": {
    "type": "RESOURCE_NOT_FOUND",
    "description": "Not found."
  }
}
```

Advanced Usage
--------------

[](#advanced-usage)

### Shutdown handler integration

[](#shutdown-handler-integration)

For complete fatal error coverage — including errors that occur outside of Slim's request lifecycle — `JsonErrorHandler` can be integrated with [andrewdyer/shutdown-handler](https://github.com/andrewdyer/shutdown-handler):

```
composer require andrewdyer/shutdown-handler
```

Wrap `JsonErrorHandler` in a `CallableErrorResponder` and register a `ShutdownHandler` before running the application:

```
use AndrewDyer\JsonErrorHandler\JsonErrorHandler;
use AndrewDyer\ShutdownHandler\Adapters\CallableErrorResponder;
use AndrewDyer\ShutdownHandler\Adapters\CallableResponseEmitter;
use AndrewDyer\ShutdownHandler\ShutdownHandler;
use Slim\Factory\AppFactory;
use Slim\Factory\ServerRequestCreatorFactory;
use Slim\ResponseEmitter;

$app = AppFactory::create();

$displayErrorDetails = true;

$errorMiddleware = $app->addErrorMiddleware(
    $displayErrorDetails,
    logErrors: true,
    logErrorDetails: true
);

$errorHandler = new JsonErrorHandler(
    $app->getCallableResolver(),
    $app->getResponseFactory(),
    logger: null
);

$errorMiddleware->setDefaultErrorHandler($errorHandler);

$request = ServerRequestCreatorFactory::create()->createServerRequestFromGlobals();

$responseEmitter = new ResponseEmitter();

$shutdownHandler = new ShutdownHandler(
    $request,
    new CallableErrorResponder(
        static fn ($request, $exception, bool $displayErrorDetails) => $errorHandler(
            $request,
            $exception,
            $displayErrorDetails,
            logError: true,
            logErrorDetails: true
        )
    ),
    new CallableResponseEmitter(
        static fn ($response) use ($responseEmitter) => $responseEmitter->emit($response)
    ),
    $displayErrorDetails
);

register_shutdown_function($shutdownHandler);

$response = $app->handle($request);

$responseEmitter->emit($response);
```

Refer to the [shutdown-handler documentation](https://github.com/andrewdyer/shutdown-handler) for full details on implementing a response emitter.

License
-------

[](#license)

Licensed under the [MIT license](https://opensource.org/licenses/MIT) and is free for private or commercial projects.

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance98

Actively maintained with recent releases

Popularity13

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

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

Total

8

Last Release

12d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/666597ea6e46748a89fe8764d1a45b4d0da97daf1bb1e9770ea34ae41f706d08?d=identicon)[andrewdyer](/maintainers/andrewdyer)

###  Code Quality

TestsPHPUnit

Code StylePHP CS Fixer

### Embed Badge

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

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

###  Alternatives

[tempest/framework

The PHP framework that gets out of your way.

2.2k31.1k11](/packages/tempest-framework)[symfony/symfony

The Symfony PHP framework

31.4k86.9M2.2k](/packages/symfony-symfony)[cakephp/cakephp

The CakePHP framework

8.8k19.1M1.7k](/packages/cakephp-cakephp)[guzzlehttp/psr7

PSR-7 message implementation that also provides common utility methods

7.9k1.1B3.7k](/packages/guzzlehttp-psr7)[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

84735.1k](/packages/flow-php-flow)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.4M506](/packages/shopware-core)

PHPackages © 2026

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