gpt4 book ai didi

symfony - API 平台错误,字段不可为空

转载 作者:行者123 更新时间:2023-12-02 10:13:25 29 4
gpt4 key购买 nike

我有一个简单的实体

 /**
* @var string|null
*
* @ORM\Column(name="city", type="string", length=255, nullable=false)
* @Assert\NotNull()
*/
private $city;

...

/**
* @param string|null $city
* @return CustomerAddressList
*/
public function setCity(?string $city): CustomerAddressList
{
$this->city = $city;
return $this;
}

如果我尝试将 null 传递给字段 city,结果是运行时异常而不是验证错误:

{
"@context": "/api/v2/contexts/Error",
"@type": "hydra:Error",
"hydra:title": "An error occurred",
"hydra:description": "The type of the address attribute must be string, NULL given."
}

如果我将 nullable=false 更改为 true,那么一切都会正常工作,但这不是一个可接受的解决方案。

如何修复它?

最佳答案

找到解决方案。

* @ApiResource(
* denormalizationContext={"disable_type_enforcement"=false}
* )

添加带有 "disable_type_enforcement"=falsedenormalizationContext 会禁用使用 Doctrine 注释对请求进行验证。

{
"@context": "/api/v2/contexts/ConstraintViolationList",
"@type": "ConstraintViolationList",
"hydra:title": "An error occurred",
"hydra:description": "city: This value should be not null",
"violations": [
{
"propertyPath": ".city",
"message": "This value should be not null."
},

如果需要强制字段为特定类型,则需要像之前的 Symfony 4.3 一样添加正确的 @Assert\Type(...)

关于symfony - API 平台错误,字段不可为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59647057/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com