tymo49 / api-exception-bundle
捕获所有 Symfony 3.3 或更高版本的错误并将其转换为 problem json RFC7807 响应
1.0.9
2020-07-24 09:11 UTC
Requires
- php: ^7.2
- guzzlehttp/guzzle: ^6.3
- phpunit/phpunit: ^6.2
- polishsymfonycommunity/symfony-mocker-container: ^1.0
- sensio/framework-extra-bundle: ^5.3
- symfony/phpunit-bridge: ^4.2
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/']