middlewares/error-handler

Middleware to handle http errors

v2.0.0 2019-05-10 14:39 UTC

README

Latest Version on Packagist Software License Build Status Quality Score Total Downloads SensioLabs Insight

Middleware to catch and format errors encountered while handling the request.

Requirements

Installation

This package is installable and autoloadable via Composer as middlewares/error-handler.

composer require middlewares/error-handler

Example

use Middlewares\ErrorFormatter;
use Middlewares\ErrorHandler;
use Middlewares\Utils\Dispatcher;

// Create a new ErrorHandler instance
// Any number of formatters can be added. One will be picked based on the Accept
// header of the request. If no formatter matches, the PlainFormatter will be used.
$errorHandler = new ErrorHandler([
    new ErrorFormatter\GifFormatter(),
    new ErrorFormatter\HtmlFormatter(),
    new ErrorFormatter\JpegFormatter(),
    new ErrorFormatter\JsonFormatter(),
    new ErrorFormatter\PngFormatter(),
    new ErrorFormatter\SvgFormatter(),
    new ErrorFormatter\XmlFormatter(),
]);

$errorHandler->defaultFormatter(new ErrorFormatter\PlainFormatter());

// ErrorHandler should always be the first middleware in the stack!
$dispatcher = new Dispatcher([
    $errorHandler,
    // ...
    function ($request) {
        throw HttpErrorException::create(404);
    }
]);

$request = $serverRequestFactory->createServerRequest('GET', '/');
$response = $dispatcher->dispatch($request);

Options

__construct(array $formatters [])

Add the formatters to be used (instances of Middlewares\ErrorFormatter\FormatterInterface).

defaultFormatter(FormatterInterface $defaultFormatter)

Set the default formatter if no content-type matches (by default is PlainFormatter).

Please see CHANGELOG for more information about recent changes and CONTRIBUTING for contributing details.

The MIT License (MIT). Please see LICENSE for more information.