soft-passio/api-exception-bundle

捕获所有 Symfony 错误并将其转换为 RFC7807 格式的 problem json 响应

安装次数: 1,117

依赖项: 0

建议者: 0

安全性: 0

星标: 0

关注者: 2

分支: 5

类型:symfony-bundle

2.2 2020-06-17 12:32 UTC

This package is auto-updated.

Last update: 2024-09-29 05:42:21 UTC


README

捕获所有 Symfony 3.3 或更高版本的错误并将其转换为 problem+json RFC7807 格式的响应

安装

使用 composer 安装此包

$ php composer.phar require soft-passio/api-exception-bundle

将包添加到 AppKernel

<?php
    // app/AppKernel.php

    public function registerBundles()
    {
        $bundles = array(
            // ...
            
            new SoftPassio\ApiExceptionBundle\ApiExceptionBundle(),
        );
    }

配置

SoftPassioApiProblemExceptionBundle 通过 ApiExceptionSubscriber 自动捕获您的错误,并返回 application/problem+json 格式的响应

{
  "detail": "Description of problem",
  "status": 404,
  "type": "about:blank",
  "title": "Not Found"
}

改变数据结构

此包提供 ResponseFactoryInterface 接口,用于覆盖响应数据,如果您想更改响应数据。

示例用法

以接收类似以下响应

{
  "exception": {
      "detail": "Description of problem",
      "status": 404,
      "type": "about:blank",
      "title": "Not Found"
  }
}

创建新的 CustomResponseFactory

<?php

...
class FBExceptionResponseFactory implements ResponseFactoryInterface
{
    public function createResponse(ApiProblemInterface $apiProblem)
    {
        $data = $apiProblem->ToArray();

        $response = new JsonResponse(
            $this->prepareData($data)
        );

        $response->headers->set('Content-Type', 'application/problem+json');

        return $response;
    }

    public function prepareData($data)
    {
        return [
            'exception' => [
                $data
            ],
        ];
    }
}

配置参考

soft_passio_api_exception:
    response_factory: SoftPassio\ApiExceptionBundle\Factory\ApiProblemResponseFactory
    enabled: true
    paths_excluded: ['/admin/']