4xxi/rest-request-errors

此包已被弃用且不再维护。未建议替代包。

提供REST请求错误序列化的包

安装数: 2,034

依赖项: 0

建议者: 0

安全性: 0

星标: 2

关注者: 4

分支: 0

开放问题: 1

类型:symfony-bundle

1.4 2020-05-07 08:57 UTC

This package is auto-updated.

Last update: 2023-07-28 15:44:21 UTC


README

该包为symfony表单错误提供简单的JSON REST API序列化。

安装

  1. 通过composer安装组件
composer require 4xxi/rest-request-errors

用法

对于Symfony表单

use Fourxxi\RestRequestError\Exception\FormInvalidRequestException;

if (!$form->isValid()) {
    throw new FormInvalidRequestException($form);
}

对于自定义错误数组

use Fourxxi\RestRequestError\Exception\ArrayInvalidRequestException;

throw new ArrayInvalidRequestException([
    'field1' => 'errorValue',
    'field2' => 'someAnotherError'
]);

上述示例生成响应

{
  "errors": [
    
  ],
  "children": {
    "username": {
      "errors": [
        "Some error for form field"
      ],
      "children": []
    }
  }
}

如果您的应用程序没有异常监听器,您可以使用包提供的异常监听器。

要启用它,请将以下内容的配置yaml添加到config/packages/rest_request_error.yaml

rest_request_error:
  use_exception_listener: true

装饰normalizer

如果您想修改错误响应负载,您可以装饰包normalizer以使用自己的

将装饰服务添加到services.yaml

App\Serializer\CustomExceptionNormalizer:
    decorates: Fourxxi\RestRequestError\Serializer\InvalidRequestExceptionNormalizer
    arguments:
        - '@App\Serializer\CustomExceptionNormalizer.inner'

并创建自己的装饰器类

final class CustomExceptionNormalizer implements NormalizerInterface
{
    /**
     * @var NormalizerInterface
     */
    private $normalizer;

    public function __construct(NormalizerInterface $normalizer)
    {
        $this->normalizer = $normalizer;
    }

    /**
     * @param InvalidRequestExceptionInterface $object
     */
    public function normalize($object, string $format = null, array $context = [])
    {
        $normalized = $this->normalizer->normalize($object, $format, $context);
        $normalized['code'] = $object->getStatusCode();

        return $normalized;
    }

    public function supportsNormalization($data, string $format = null)
    {
        return $this->normalizer->supportsNormalization($data, $format);
    }
}

结果

{
  "errors": [],
  "children": {
    "test": {
      "errors": [
        "foo"
      ],
      "children": []
    }
  },
  "code": 400
}