API 不可空字段的平台错误
API Platform error with not nullable field
我有一个简单的实体
/**
* @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}
* )
添加 denormalizationContext
和 "disable_type_enforcement"=false
禁用使用 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."
},
如果有必要将字段强制为特定类型,则有必要添加正确的 @Assert\Type(...)
作为 Symfony 4.3
我有一个简单的实体
/**
* @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}
* )
添加 denormalizationContext
和 "disable_type_enforcement"=false
禁用使用 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."
},
如果有必要将字段强制为特定类型,则有必要添加正确的 @Assert\Type(...)
作为 Symfony 4.3