app-verk/api-exception-bundle

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

安装数: 6,986

依赖关系: 0

建议者: 0

安全性: 0

星标: 1

关注者: 7

分支: 5

开放问题: 0

类型:symfony-bundle

1.0.6 2020-12-22 08:07 UTC

This package is auto-updated.

Last update: 2024-08-29 04:01:46 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/']