为了账号安全,请及时绑定邮箱和手机立即绑定

如何设置 DataPersister 的响应代码

如何设置 DataPersister 的响应代码

PHP
千巷猫影 2022-12-23 10:11:49
我正在使用 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();    }
查看完整描述

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

您可以在错误处理章节中找到更多信息



查看完整回答
反对 回复 2022-12-23
  • 1 回答
  • 0 关注
  • 73 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号