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. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. andrewdyer/json-error-handler

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

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

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

0.2.8(1mo ago)083MITPHPPHP ^8.3CI passing

Since Apr 15Pushed 1mo 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 3w ago

READMEChangelog (10)Dependencies (16)Versions (12)Used By (0)

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.

[![Latest Stable Version](https://camo.githubusercontent.com/ec1c896a69d157fbd10fe4f4bbd86c51714efe1d984a70c7c38a1e45249b6dbe/687474703a2f2f706f7365722e707567782e6f72672f616e64726577647965722f6a736f6e2d6572726f722d68616e646c65722f763f7374796c653d666c61742d737175617265)](https://packagist.org/packages/andrewdyer/json-error-handler)[![Total Downloads](https://camo.githubusercontent.com/505e756a7fdfa4bbf5ca914918ed9df1caf43a9a8ecd75f929cf48c9dd77dc7d/687474703a2f2f706f7365722e707567782e6f72672f616e64726577647965722f6a736f6e2d6572726f722d68616e646c65722f646f776e6c6f6164733f7374796c653d666c61742d737175617265)](https://packagist.org/packages/andrewdyer/json-error-handler)[![License](https://camo.githubusercontent.com/38c2affe5254d02faba7c93cffd793399022059cf5edfafb95d35e8053fb3fa5/687474703a2f2f706f7365722e707567782e6f72672f616e64726577647965722f6a736f6e2d6572726f722d68616e646c65722f6c6963656e73653f7374796c653d666c61742d737175617265)](https://packagist.org/packages/andrewdyer/json-error-handler)[![PHP Version Require](https://camo.githubusercontent.com/f1eb110b3715157a5089a73bbf06c49ea2addbb6e2cbc77b0a01aefc84f189a6/687474703a2f2f706f7365722e707567782e6f72672f616e64726577647965722f6a736f6e2d6572726f722d68616e646c65722f726571756972652f7068703f7374796c653d666c61742d737175617265)](https://packagist.org/packages/andrewdyer/json-error-handler)

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

[](#introduction)

This library extends Slim Framework's built-in error handling to intercept exceptions and transform them into well-formed JSON responses with appropriate HTTP status codes. It supports optional error detail exposure for debug environments and integrates directly with Slim's error middleware. For shutdown handling workflows, it can be paired with [andrewdyer/shutdown-handler](https://github.com/andrewdyer/shutdown-handler) to keep unhandled error responses consistent.

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

40

—

FairBetter than 86% of packages

Maintenance92

Actively maintained with recent releases

Popularity9

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

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

Total

10

Last Release

38d ago

### Community

Maintainers

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

---

Top Contributors

[![andrewdyer](https://avatars.githubusercontent.com/u/8114523?v=4)](https://github.com/andrewdyer "andrewdyer (14 commits)")

---

Tags

error-handlerexceptionsjsonphpslimslim-frameworkphpjsonslimexceptionserror-handlerslim-framework

###  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.2k34.4k16](/packages/tempest-framework)[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

85036.3k](/packages/flow-php-flow)[algolia/algoliasearch-client-php

API powering the features of Algolia.

69735.1M162](/packages/algolia-algoliasearch-client-php)[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.6M600](/packages/shopware-core)[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)[pagemachine/typo3-formlog

Form log for TYPO3

23238.6k8](/packages/pagemachine-typo3-formlog)

PHPackages © 2026

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