1 回答

TA贡献1836条经验 获得超3个赞
你应该抛出一个异常,然后你应该配置你的 api_platform 来处理这个异常。ApiPlatform 会将异常转换为带有消息和指定代码的响应。
第一步:创建专用的异常类
<?php
// api/src/Exception/ProductNotFoundException.php
namespace App\Exception;
final class AdminNonDeletableException extends \Exception
{
}
第 2 步:在您的数据持久性中,抛出异常:
public function remove($data, array $context = [])
{
/* @var Admin $data */
#The Manager can never be deleted:
if( $data->getManager() ){
throw new AdminNonDeletableException('thisAdminIsManager');
}
$this->manager->remove($data);
$this->manager->flush();
}
Step3:在 config/package/api_platform.yaml 文件中添加你的异常并声明代码编号 (414)
# config/packages/api_platform.yaml
api_platform:
# ...
exception_to_status:
# The 4 following handlers are registered by default, keep those lines to prevent unexpected side effects
Symfony\Component\Serializer\Exception\ExceptionInterface: 400 # Use a raw status code (recommended)
ApiPlatform\Core\Exception\InvalidArgumentException: !php/const Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST
ApiPlatform\Core\Exception\FilterValidationException: 400
Doctrine\ORM\OptimisticLockException: 409
# Custom mapping
App\Exception\AdminNonDeletableException: 414 # Here is the handler for your custom exception associated to the 414 code
您可以在错误处理章节中找到更多信息
- 1 回答
- 0 关注
- 73 浏览
添加回答
举报