Middleware

Error Handling Middleware

Handle and log errors with virtually zero configuration in Kipchak.

Introduction

The Error Middleware intercepts unhandled exceptions and PHP errors within your application. It converts them into standardized, API-friendly JSON responses, ensuring that your API consumers never encounter raw HTML stack traces or silent failures.

Key features include:

  • Automated JSON Formatting: Catches all Throwables and returns a structured JSON payload.
  • Environment Awareness: Displays detailed stack traces when debug is enabled, and generic messages in production.
  • Logging Integration: Automatically logs exceptions to the built in logger (e.g., Monolog) based on your verbosity settings.

Installation

Install the middleware via composer by running:

composer require kipchak/middleware-error

Configuration

Unlike other middlewares, the Error Middleware typically relies on your global application configuration found in kipchak.api.php. It uses the global logging flags to determine its behaviour.

Configuration Keys

The below properties are configured in kipchak.api.php.

  • debug (bool):
    • This middleware does not read it. An error gets the same response with it on or off, so a stack trace never reaches a client. Use the logging settings below to see the detail.
  • logExceptions (bool):
    • If true, exceptions are sent to the registered Logger instance.
  • logExceptionDetails (bool):
    • If true, the log entry will include the full stack trace.
  • logExceptionsTo (string, optional):
    • 'error_log' (the default): Slim writes exceptions with PHP's error_log(), as in earlier versions.
    • 'logger': exceptions go through the Logger driver instead, at error level, so they share your API's log format and pass through its processors, such as PII Redaction's. Without the Logger driver, error_log() is used. Requires kipchak/middleware-error 1.29 or later.

Example Configuration

<?php

use function Kipchak\Core\env;

return [
    // ... other settings ...
    'debug' => filter_var(env('DEBUG', 'false'), FILTER_VALIDATE_BOOLEAN),
    'logExceptions' => true,
    'logExceptionDetails' => true,
    // 'logExceptionsTo' => 'logger',
];

Usage

Initialise it twice in middlewares/middlewares.php, as the first and the last line, with every other global middleware between the two:

use Kipchak\Middleware\Error\Error;

Error::initialise($app);   // innermost: turns route exceptions into JSON responses
// ... every other global middleware
Error::initialise($app);   // outermost: does the same for exceptions from the middleware above

Slim runs the middleware added last first. The first is therefore the innermost middleware: it answers an exception thrown by a route, and the middleware around it, such as OpenTelemetry, Metering and Redaction, sees the JSON response. The last is the outermost: it answers an exception thrown by any other middleware, which would otherwise reach the client as a plain-text 500. See Middleware.

Status names

A Slim HTTP exception thrown by a route or a middleware becomes the response envelope, with its status code, a status name and its message as data:

{"code": 429, "status": "TOO_MANY_REQUESTS", "data": "Slow down."}
ExceptionCodestatus
HttpBadRequestException400BAD_REQUEST
HttpUnauthorizedException401UNAUTHENTICATED
HttpForbiddenException403INSUFFICIENT_PRIVILEGES
HttpNotFoundException404RESOURCE_NOT_FOUND
HttpMethodNotAllowedException405NOT_ALLOWED
HttpTooManyRequestsException, or any HttpException with code 429429TOO_MANY_REQUESTS (since 1.34)
HttpNotImplementedException501NOT_IMPLEMENTED
Any other exception500, or the HttpException's own codeSERVER_ERROR

Only an HttpException's message is passed to the client. Any other exception's message can carry credentials or internal detail, so the client receives An unexpected error occurred. instead.

An invalid request body

From 1.36, a body refused by Dto\Input also carries meta.errors, what is wrong with each field by its path, beside the same message in data. Any other error has no meta.

{
    "code": 400,
    "status": "BAD_REQUEST",
    "meta": {"errors": {"title": ["Must be at least 1 character."]}},
    "data": "The book is not valid: title: Must be at least 1 character."
}

Response Formats

Every error has the same shape, with the status from Status names.

An exception a route throws on purpose, a Slim HttpException such as HttpNotFoundException, passes its message to the client, so write it for the client:

{
    "code": 404,
    "status": "RESOURCE_NOT_FOUND",
    "data": "No book has the ID 9."
}

Any other exception is masked, because its message can hold credentials or internal detail:

{
    "code": 500,
    "status": "SERVER_ERROR",
    "data": "An unexpected error occurred."
}

The exception itself goes to the logs when logExceptions is on, with its stack trace when logExceptionDetails is on.

Git Repository

The source code for this middleware is available on 1x.ax at https://1x.ax/mamluk/kipchak/middlewares/error.

Previous
Auth - Request Signing