将 null 传递给字符串字段时,API 平台返回类型错误而不是验证错误 [英] API Platform returns type error instead of validation error when passing null to a string field
问题描述
我正在使用
验证结构示例
感谢 Symfony Slack 频道 #api-platform 中的人解决了这个问题.
在序列化过程中使用了 Doctrine 列定义,以便解决问题,需要 nullable=true
.添加后,序列化过程开始工作,并在验证级别捕获空值,返回预期的响应结构.
I'm using API Platform v2.2.5, and in the process of writing tests for my resources I've discovered that, when null
is provided for a field of type string
, an error response is being returned during the denormalization process, which includes a non client-friendly message and a stack trace. This is different to if an empty string is provided or the field is omitted completely, which returns a structured validation response. How can I instead return a validation error response as when an empty string is provided?
Entity
class MyEntity
{
/**
* @var string|null
*
* @ORM\Column(type="string", length=255)
*
* @Assert\NotBlank
*
* @Groups({"read", "write"})
*/
private $title;
/**
* @return null|string
*/
public function getTitle(): ?string
{
return $this->title;
}
/**
* @param string $title
* @return WorkoutTemplate
*/
public function setTitle(?string $title): self
{
$this->title = $title;
return $this;
}
}
Resource configuration
App\Entity\MyEntity:
collectionOperations
post:
denormalization_context:
groups:
- write
Error response
Example of validation structure
Figured it out thanks to the guys in the Symfony Slack channel #api-platform.
The Doctrine column definitions are used during the serialization process so to fix the issue, nullable=true
was required. Once that was added, the serialization process worked and the null value was caught at the validation level, returning the expected response structure.
这篇关于将 null 传递给字符串字段时,API 平台返回类型错误而不是验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!