我正在使用 API 平台 v2.2.5,在为我的资源编写测试的过程中,我发现,当为
null
类型的字段提供 string
时,将返回错误响应在非规范化过程中,包括非客户端友好消息和堆栈跟踪。这与提供空字符串或完全省略该字段的情况不同,后者返回结构化验证响应。当提供空字符串时,如何返回验证错误响应?
实体
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;
}
}
资源配置
App\Entity\MyEntity:
collectionOperations
post:
denormalization_context:
groups:
- write
多亏了 Symfony Slack 频道#api-platform 中的人,才弄明白了。
在序列化过程中使用了 Doctrine 列定义,因此要解决此问题,
nullable=true
是必需的。添加后,序列化过程开始工作,空值在验证级别被捕获,返回预期的响应结构。
问题可以通过在
COLLECT_DENORMALIZATION_ERRORS
中设置
denormalizationContext
标志来解决
denormalizationContext: [
DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS => true
]
这样你会得到一个 422
ConstraintVoilationsList
验证错误响应,而不是 400 或 500