问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/50081174/api-platform-returns-type-error-instead-of-validation-error-when-passing-null-to