middlewares / error-handler
处理HTTP错误的中间件
v3.0.1
2020-12-03 01:13 UTC
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
用于捕获和格式化处理请求过程中遇到的错误的中间件。
要求
- PHP >= 7.2
- PSR-7 http 库
- PSR-15 中间件分发器
安装
此软件包可以通过Composer安装和自动加载,地址为 middlewares/error-handler。
composer require middlewares/error-handler
示例
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);
用法
添加要使用的 格式化器(Middlewares\ErrorFormatter\FormatterInterface 实例)。如果没有提供格式化器,则使用所有可用的格式化器。
$errorHandler = new ErrorHandler([ new ErrorFormatter\HtmlFormatter(), new ErrorFormatter\JsonFormatter() ]);
注意:如果没有找到格式化器,将使用数组中的第一个值。在上面的示例中,是 HtmlFormatter。
请参阅 CHANGELOG 了解有关最近更改的更多信息,以及 CONTRIBUTING 了解贡献详情。
MIT 许可证 (MIT)。有关更多信息,请参阅 LICENSE。