如何在“/api”文档 api-platform 上添加我的自定义错误

问题描述 投票:0回答:2

我正在使用 Symfony 4 和 Api-Platform 开发一个应用程序。

我根据

这些文档
创建了一个自定义错误xxxException。我在术后使用它,效果很好。

现在我想在访问

some-url/api
时公开 API 文档中的错误。

如何做到,才会出现下图这样的情况?

symfony error-handling api-platform.com
2个回答
4
投票

您可以按照

此处
的说明创建SwaggerDecorator

然后在

App\Swagger\SwaggerDecorator
方法中的
normalize
类中,您可以像这样更改文档(这里是添加文档和对自定义登录操作的响应的示例):

public function normalize($object, $format = null, array $context = [])
{
    $documentation = $this->decorated->normalize($object, $format, $context);

    $documentation['paths']['/login'] = [ // "/login" is the path of the operation
        'post' => [ // "post" is the http request method
            'responses' => [
                '200' => [ // 200 is the http response code
                    'description' => 'Successful log in.',
                ],
                '401' => [ // 401 another http response code
                    'description' => 'Bad credentials.',
                ],
            ],
        ],
    ];

    return $documentation;
}

注意:文档变量只是一个数组或一个实现

ArrayAccess
的对象,您可以转储它并根据需要进行编辑。


2
投票

基于 Simeons 的回答,我想补充一点,他的示例覆盖了“/login”示例的所有键,因为他覆盖了该后操作的完整数组。

如果您只想覆盖或添加特定http状态代码的文档,那么您可以这样做

public function normalize($object, $format = null, array $context = [])
    {
        $docs = $this->decorated->normalize($object, $format, $context);

        // Document custom errors that we get from exceptions registered in config/packages/api_platform.yaml
        $docs['paths']['/api/books']['post']['responses']['409'] = ['description' => 'The book is no longer available'];

        return $docs;
    }

您可以通过将自定义异常映射到 config/packages/api_platform.yaml 中的代码来添加配置 http 状态代码

api_platform:
    mapping:
        paths: ['%kernel.project_dir%/src/Entity']
    exception_to_status:
        # The 4 following handlers are registered by default, keep those lines to prevent unexpected side effects
        Symfony\Component\Serializer\Exception\ExceptionInterface: 400 # Use a raw status code (recommended)
        ApiPlatform\Core\Exception\InvalidArgumentException: 'HTTP_BAD_REQUEST' # Or a `Symfony\Component\HttpFoundation\Response`'s constant
        ApiPlatform\Core\Exception\FilterValidationException: 400
        Doctrine\ORM\OptimisticLockException: 409

        # Custom mapping
        App\Exception\SpaceUnavailableException: 409
© www.soinside.com 2019 - 2024. All rights reserved.