php Shopware 6管理:捕获API错误

k5hmc34c  于 2023-04-04  发布在  PHP
关注(0)|答案(1)|浏览(141)

在我的自定义插件中,我向服务器发送了一个write请求,服务器响应一个系统(500)错误:
POST http://0.0.0.0:8080/api/my-entity 500 (Internal Server Error)
该错误是已知且预期的,它来自数据库,因为重复的条目:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'test' for key 'my_entity.name'
但是在服务器端如何或者在哪里捕获和处理错误来清理错误消息呢?I have found this description,但是我将处理error before 响应以避免http错误。

s8vozzvw

s8vozzvw1#

你可以使用PreWriteValidationEvent来抛出你的自定义异常或者抑制一个异常。但是无论哪种方式,你都必须首先检查非唯一的值。

class MyEntityValidationSubscriber implements EventSubscriberInterface
{
    private EntityRepository $myEntityRepository;

    public function __construct(EntityRepository $myEntityRepository) 
    {
        $this->myEntityRepository = $myEntityRepository
    }

    public static function getSubscribedEvents(): array
    {
        return [
            PreWriteValidationEvent::class => 'onPreWriteValidate',
        ];
    }

    public function onPreWriteValidate(PreWriteValidationEvent $event): void
    {
        foreach ($event->getCommands() as $command) {
            if ($command instanceof DeleteCommand || $command->getEntityName() !== 'my_entity') {
                continue;
            }

            $payload = $command->getPayload();

            if (!\array_key_exists('name', $payload)) {
                continue;
            }

            $criteria = new Criteria();
            $criteria->addFilter(new EqualsFilter('name', $payload['name']));
            $existingEntity = $this->myEntityRepository->searchIds($criteria, $event->getContext())->firstId();

            if ($existingEntity === null) {
                continue;
            }

            throw new MyEntityDuplicateNameException();
        }
    }
}
class MyEntityDuplicateNameException extends ShopwareHttpException
{
    public function __construct()
    {
        parent::__construct('Field name of my_entity must be unique.');
    }

    public function getErrorCode(): string
    {
        return 'MY_PLUGIN__MY_ENTITY_DUPLICATE_NAME';
    }

    public function getStatusCode(): int
    {
        return Response::HTTP_BAD_REQUEST;
    }
}

相关问题