如何设置 DataPersister 的响应代码

我正在使用 Symfony 4.4 / API 平台,我正在尝试从 DataPersister 返回响应或设置其代码。


在我的 DataPersister 中,我测试 Admin->isManager() 是否为真,因此永远无法删除 Admin,因此在这种情况下,我想在响应 414 中返回一个自定义状态代码,以及一条消息“thisAdminIsManager”


AdminDataPersister:

final class AdminDataPersister implements ContextAwareDataPersisterInterface

{

    /* @var EntityManagerInterface */

    private $manager;


    public function __construct(

        EntityManagerInterface $manager

    ){

        $this->manager = $manager;

    }



    public function supports($data, array $context = []): bool

    {

        return $data instanceof Admin;

    }


    public function persist($data, array $context = [])

    {   

        $this->manager->persist($data);

        $this->manager->flush();

    }


    public function remove($data, array $context = [])

    {

        /* @var Admin $data */

        #The Manager can never be deleted:

        if( $data->getManager() ){

            return; //here I want to return the custom response

        }

        $this->manager->remove($data);

        $this->manager->flush();


    }


千巷猫影
浏览 164回答 1
1回答

米脂

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