middlewares / error-handler
Middleware to handle http errors
Installs: 86 962
Dependents: 11
Suggesters: 0
Security: 0
Stars: 14
Watchers: 3
Forks: 6
Open Issues: 0
Requires
- php: ^7.2 || ^8.0
- middlewares/utils: ^3.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.0
- laminas/laminas-diactoros: ^2.3
- oscarotero/php-cs-fixer-config: ^1.0
- phpstan/phpstan: ^0.12
- phpunit/phpunit: ^8|^9
- squizlabs/php_codesniffer: ^3.0
README
Middleware to catch and format errors encountered while handling the request.
Requirements
- PHP >= 7.2
- A PSR-7 http library
- A PSR-15 middleware dispatcher
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 first formatter in the array // will be used. $errorHandler = new ErrorHandler([ new ErrorFormatter\HtmlFormatter(), new ErrorFormatter\ImageFormatter(), new ErrorFormatter\JsonFormatter(), new ErrorFormatter\PlainFormatter(), new ErrorFormatter\SvgFormatter(), new ErrorFormatter\XmlFormatter(), ]); // 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);
Usage
Add the formatters to be used (instances of Middlewares\ErrorFormatter\FormatterInterface
). If no formatters are provided, use all available.
$errorHandler = new ErrorHandler([ new ErrorFormatter\HtmlFormatter(), new ErrorFormatter\JsonFormatter() ]);
Note: If no formatter is found, the first value of the array will be used. In the example above, HtmlFormatter
.
Please see CHANGELOG for more information about recent changes and CONTRIBUTING for contributing details.
The MIT License (MIT). Please see LICENSE for more information.