riper / exception-transformer
在内核捕获之前转换异常的包
v2.0.0
2021-05-19 10:15 UTC
Requires
- php: >=7.4
- symfony/framework-bundle: ^4
Requires (Dev)
- phpunit/phpunit: ^9
This package is auto-updated.
Last update: 2024-09-19 17:36:25 UTC
README
此包可以监听到达Symfony内核的异常,并在内核渲染它们之前对它们进行转换。当你想将代码中的域/业务异常转换为表示异常,如包含HTTP状态码的HTTP异常时,这非常有用。
用法
在composer.json中添加依赖项
对于symfony >=4 和 php >=7.4
"riper/exception-transformer" : "2.*"
对于symfony <4 和 php <7.4
"riper/exception-transformer" : "1.*"
在app-kernel中注册包
new Riper\Bundle\ExceptionTransformerBundle\RiperCommonExceptionTransformerBundle(),
使用服务转换异常(最便携的方式)
实现接口 \Riper\Bundle\ExceptionTransformerBundle\ExceptionTransformer\ExceptionTransformerInterface
实现 transform 方法。根据提供的异常,它可以(如果需要)抛出一个新的异常。
示例
<?php namespace Riper\Bundle\Moderation\AmoBundle\Exceptions; use Riper\Bundle\Accounts\AuthenticationBundle\Exceptions\NotFoundException; use Riper\Bundle\ExceptionTransformerBundle\ExceptionTransformer\ExceptionTransformerInterface; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; class ExceptionTransformer implements ExceptionTransformerInterface { /** * {@inheritdoc} */ public function transform(\Exception $exception) { switch (1){ case $exception instanceof NotFoundException : throw new NotFoundHttpException($exception->getMessage(),$exception); case $exception instanceof InvalidParametersException : throw new BadRequestHttpException($exception->getMessage(),$exception); } } }
创建一个带有以下信息的服务描述
- name : riper.exception.transformer
- scope: [转换器将被限制到的命名空间]
示例
riper.moderation.exception.transformer: class: Riper\Bundle\biduleBundle\Exceptions\ExceptionTransformer tags: - { name: riper.exception.transformer , namespace_scope: "Riper\\Bundle\\Bidule\\"}
使用内置的转换器来处理HTTP错误异常
您可以通过添加一些配置来将来自 symfony/http-kernel 的异常转换为httpException,无需编写代码。
- 在参数中创建一个以 unique name 结尾的配置键,后缀为 "riper_exception_map"。
- 该参数包含key=>value,其中
- key = 需要转换的异常的完整命名空间(不包括开头的斜杠)
- value = 要生成的HTTP状态(将抛出一个具有适当HTTP状态码的异常)
可用状态的列表位于 riper_exception_mapping.shortcuts 参数中,位于 ExceptionTransformerBundle/Resources/config/exceptions_mapping.yml。以下是一个不完整的列表
- BadRequestHttpException
- NotFoundHttpException
- ConflictHttpException
- AccessDeniedHttpException
- GoneHttpException
- LengthRequiredHttpException
- MethodNotAllowedHttpException
- NotAcceptableHttpException
- PreconditionFailedHttpException
- PreconditionRequiredHttpException
- UnprocessableEntityHttpException
- UnsupportedMediaTypeHttpException
示例
parameters:
customercare.contact.riper_exception_map:
Riper\Bundle\CustomerCare\ContactBundle\Exceptions\InvalidParameterException: BadRequestHttpException
Riper\Bundle\CustomerCare\ContactBundle\Exceptions\ContactException: BadRequestHttpException
状态码/异常不在快捷列表中?请使用带有转换器标签的第一个方法