API Platform returns type error instead of validation error when passing null to a string field

送分小仙女□ 提交于 2021-02-10 19:55:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!