app-verk / api-exception-bundle
捕获所有 Symfony 3.3 或更高版本的错误并将其转换为 RFC7807 格式的 problem json 响应
1.0.6
2020-12-22 08:07 UTC
Requires
- php: ^7.2
- guzzlehttp/guzzle: ^5.0 || ^6.0 || ^7.0
- phpunit/phpunit: ^6.2 || ^8.3
- polishsymfonycommunity/symfony-mocker-container: ^1.0
- sensio/framework-extra-bundle: ^5.3
- symfony/phpunit-bridge: ^4.2
This package is auto-updated.
Last update: 2024-08-29 04:01:46 UTC
README
捕获所有 Symfony 3.3 或更高版本的错误并将其转换为 problem+json RFC7807 格式的响应
安装
使用 composer 安装此包
$ php composer.phar require app-verk/api-exception-bundle
将包添加到 AppKernel
<?php
// app/AppKernel.php
public function registerBundles()
{
$bundles = array(
// ...
new AppVerk\ApiExceptionBundle\AppVerkApiExceptionBundle(),
);
}
配置
AppVerkApiProblemExceptionBundle 通过 ApiExceptionSubscriber
自动捕获您的错误,并返回 application/problem+json
格式的响应
{
"detail": "Description of problem",
"status": 404,
"type": "about:blank",
"title": "Not Found"
}
更改数据结构
如果需要更改响应数据,该包提供了 ResponseFactoryInterface
以覆盖响应数据
示例用法
接收如下响应
{
"exception": {
"detail": "Description of problem",
"status": 404,
"type": "about:blank",
"title": "Not Found"
}
}
创建新的 CustomResponseFactory
<?php
...
class FBExceptionResponseFactory implements ResponseFactoryInterface
{
public function createResponse(ApiProblemInterface $apiProblem)
{
$data = $apiProblem->ToArray();
$response = new JsonResponse(
$this->prepareData($data)
);
$response->headers->set('Content-Type', 'application/problem+json');
return $response;
}
public function prepareData($data)
{
return [
'exception' => [
$data
],
];
}
}
配置参考
app_verk_api_exception:
response_factory: AppVerk\ApiExceptionBundle\Factory\ApiProblemResponseFactory
enabled: true
paths_excluded: ['/admin/']