【发布时间】:2020-03-27 03:49:18
【问题描述】:
开始之前:我查看了以下链接,但没有一个与我的问题相符:
- Swagger - Specify Optional Object Property or Multiple Responses
- Swagger; specify two responses with same code based on optional parameter
- Swagger - Specify Optional Object Property or Multiple Responses
所以,我有一个端点的 OpenAPI 3 定义,它为成功调用返回给定的有效负载(例如200 OK)。但是,对于不成功的调用(例如408 CONFLICT),我想返回一个完全不同的错误负载。
你可以看到下面的定义:
openapi: 3.0.1
info:
title: Dogs
description: API to add dogs into a database
version: 0.0.1
paths:
/dog:
post:
description: Saves a dog into the database
requestBody:
content:
application/json:
schema:
$ref: "#/components/schemas/Dog"
responses:
201:
description: A dog was added to the system
content:
application/json:
schema:
$ref: "#/components/schemas/Dog"
400:
description: This dog already exist in the system
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
components:
schemas:
Dog:
type: object
properties:
name:
type: string
description: Name of the dog
example: "barky"
Error:
type: object
properties:
code:
type: string
description: Machine-readable code of the error.
example: "Already Exists"
message:
type: string
description: A Human-readable error message.
example: "Empty string is not a valid name for a dog"
由此,我生成了一个Spring 代码(当前使用Swagger editor)。与定义关联的方法签名如下所示:
ResponseEntity<Dog> dogPost(@ApiParam(value = "" ) @Valid @RequestBody Dog body);
因此 - 我无法在此函数中返回 Error 对象,除非引发异常并稍后捕获 - 我认为这是一种不好的做法,因为无效输入的操作不是异常。
有没有办法很好地解决这个问题而不会抛出异常并将其捕获到函数范围之外?
【问题讨论】:
-
您的 OpenAPI 定义是正确的。这是一个代码生成问题 - github.com/swagger-api/swagger-codegen/issues/4693
-
这就是我所害怕的——感谢您的帮助!
标签: java spring-boot swagger openapi