【问题标题】:API Platform returns type error instead of validation error when passing null to a string field将 null 传递给字符串字段时,API 平台返回类型错误而不是验证错误
【发布时间】:2018-04-28 21:20:29
【问题描述】:

我正在使用API Platform v2.2.5,在为我的资源编写测试的过程中,我发现,当为string 类型的字段提供null 时,会出现错误响应在非规范化过程中返回,其中包括非客户端友好的消息和堆栈跟踪。这与提供空字符串或完全省略字段不同,后者返回结构化验证响应。当提供空字符串时,我如何才能返回验证错误响应?

实体

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 validation api-platform.com


    【解决方案1】:

    感谢 Symfony Slack 频道#api-platform 中的家伙们。

    在序列化过程中使用了 Doctrine 列定义,因此需要 nullable=true 来解决此问题。添加后,序列化过程开始工作,并且在验证级别捕获空值,返回预期的响应结构。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-03
      • 2019-11-27
      • 1970-01-01
      • 2020-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多