如何设置 DataPersister 的响应代码

How can I set the response code from the DataPersister

我正在使用 Symfony 4.4/API 平台,我正在尝试 return 来自 DataPersister 的响应或设置其代码。

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

A​​dminDataPersister:

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();

    }

你应该抛出一个异常,然后你应该配置你的 api_platform 来处理这个异常。 ApiPlatform 会将异常转换为带有消息和指定代码的响应。

步骤 1: 创建专用异常 class

<?php
// api/src/Exception/ProductNotFoundException.php

namespace App\Exception;

final class AdminNonDeletableException extends \Exception
{
}

Step2: 在你的数据持久化中,抛出异常:

    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

您可以在 error handling chapter

中找到更多信息