承接 4xxi/rest-request-errors 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

4xxi/rest-request-errors

最新稳定版本:1.4

Composer 安装命令:

composer require 4xxi/rest-request-errors

包简介

Bundle providing serialization of REST request errors

README 文档

README

Bundle provides simple serialization for symfony form errors in JSON REST API.

Installation

  1. Install component via composer
composer require 4xxi/rest-request-errors

Usage

For Symfony forms:

use Fourxxi\RestRequestError\Exception\FormInvalidRequestException;

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

For custom errors array:

use Fourxxi\RestRequestError\Exception\ArrayInvalidRequestException;

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

Examples above produces response:

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

If your application doesn't have exception listener, you can use bundle provided exception listener.

To enable it, add configuration yaml into config/packages/rest_request_error.yaml with following content:

rest_request_error:
  use_exception_listener: true

Decorating normalizer

If you want to modify errors response payload, you can decorate bundle normalizer with your own

Add to services.yaml decorate service

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

And create own decorator class:

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);
    }
}

Result:

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

统计信息

  • 总下载量: 2.16k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 1
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 4
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-01-24

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固