phpro / api-problem-bundle
Symfony的RFC7807问题详情集成
1.7.0
2024-02-23 12:50 UTC
Requires
- php: ~8.1.0 || ~8.2.0 || ~8.3.0
- phpro/api-problem: ^1.0
- symfony/dependency-injection: ^5.4 || ^6.0 || ^7.0
- symfony/event-dispatcher: ^5.4 || ^6.0 || ^7.0
- symfony/http-kernel: ^6.4 || ^7.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.39
- matthiasnoback/symfony-dependency-injection-test: ^4.3
- phpro/grumphp-shim: ^2.3
- phpspec/prophecy: ^1.17
- phpspec/prophecy-phpunit: ^2.0
- phpunit/phpunit: ^9.5
- symfony/security-core: ^5.4 || ^6.0 || ^7.0
README
API问题包
本包提供了一个RFC7807问题详情异常监听器,用于Symfony。在内部,本包使用了由phpro/api-problem
提供的模型。当触发ApiProblemException
时,此包将返回正确的响应。
安装
composer require phpro/api-problem-bundle
如果你没有使用symfony/flex
,你必须手动将包添加到你的包文件中
// config/bundles.php return [ // ... Phpro\ApiProblemBundle\ApiProblemBundle::class => ['all' => true], ];
支持响应格式
- application/problem+json
工作原理
use Phpro\ApiProblem\Exception\ApiProblemException; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; class SomeController { /** * @Route('/some-route', defaults={"_format" = "json"}) */ public function someAction() { throw new ApiProblemException( new HttpApiProblem('400', 'It aint all bad ...') ); } }
当控制器标记为“json”格式时,请求的Content-Type
是*/json
或请求的Accept
头部的第一个值包含json(即application/json, text/html
),此包将介入。它将异常转换为以下响应
头部
Content-Type: application/problem+json
正文
{ "status": 400, "type": "http:\/\/www.w3.org\/Protocols\/rfc2616\/rfc2616-sec10.html", "title": "Bad Request", "detail": "It ain't all bad ..." }
作为替代,可以使用ApiProblemHttpException
而不是ApiProblemException
,以便可以从日志中排除特定的状态码(参考链接)
添加自定义异常转换
目前,我们自动将以下包的异常转换为ApiProblem实例
- phpro/api-problem
- symfony/http-kernel
- symfony/security
除此之外,所有其他错误都转换为基本的ExceptionApiProblem
实例。
如果你想要添加自定义转换,你可以实现ExceptionTransformerInterface
并在symfony容器中使用phpro.api_problem.exception_transformer
标签进行注册。
use Phpro\ApiProblemBundle\Transformer\ExceptionTransformerInterface; class MyTransformer implements ExceptionTransformerInterface { public function transform(\Throwable $exception): ApiProblemInterface { return new MyApiProblem($exception); } public function accepts(\Throwable $exception): bool { return $exception instanceof MyException; } }
关于
提交错误和功能请求
错误和功能请求在GitHub上跟踪。请在贡献代码之前查看我们的规则。
许可证
api-problem-bundle遵循MIT许可证。