我正在使用symfony 4和api-platform开发一个非常棒的程序包。
我基于https://api-platform.com/docs/core/errors/创建了一个自定义错误xxxException
。我在后期操作中使用了它,效果很好。
现在,我想在访问some-url/api
时在api文档中公开我的错误。
操作方法如下图。
答案 0 :(得分:1)
您可以按照here的说明创建一个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;
}
注意:documentation变量只是实现ArrayAccess
的数组或对象,您可以将其转储并根据需要进行编辑。
答案 1 :(得分:1)
在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