tymo49/api-exception-bundle

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

安装: 22

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分叉: 5

类型:symfony-bundle

1.0.9 2020-07-24 09:11 UTC

This package is auto-updated.

Last update: 2024-09-24 19:40:48 UTC


README

Build Status

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

安装

使用 composer 安装此包

$ php composer.phar require app-verk/api-exception-bundle

将包添加到 AppKernel

<?php
    // app/AppKernel.php

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

配置

AppVerkApiProblemExceptionBundle 通过 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
            ],
        ];
    }
}

配置参考

app_verk_api_exception:
    response_factory: AppVerk\ApiExceptionBundle\Factory\ApiProblemResponseFactory
    enabled: true
    paths_excluded: ['/admin/']