Kos*_*801 7 java rest error-handling swagger swagger-codegen
我想在 Swagger 生成的 API 中使用不同的结果对象进行响应。对象的类型取决于结果代码。但 Swagger codegen 似乎只生成允许返回第一个定义/使用的类型的代码。
在正常和错误情况下返回不同对象的 Swagger 定义示例如下:
swagger: "2.0"
info:
description: "API"
version: 1.0.0
title: Example
host: localhost:8080
schemes:
- http
paths:
/exampleCall:
get:
operationId: exampleCall
produces:
- application/json
responses:
200:
description: OK
schema:
$ref: '#/definitions/exampleResponse'
400:
description: Error
schema:
$ref: '#/definitions/exampleError'
definitions:
exampleResponse:
type: object
properties:
result:
type: string
exampleError:
type: object
properties:
code:
type: string
Run Code Online (Sandbox Code Playgroud)
然后由 SwaggerCodeGen 生成以下 API 接口
@Validated
@Api(value = "exampleCall", description = "the exampleCall API")
@RequestMapping(value = "")
public interface ExampleCallApi {
ExampleCallApiDelegate getDelegate();
@ApiOperation(value = "", nickname = "exampleCall", notes = "", response = ExampleResponse.class, tags={ })
@ApiResponses(value = {
@ApiResponse(code = 200, message = "OK", response = ExampleResponse.class),
@ApiResponse(code = 400, message = "Error", response = ExampleError.class) })
@RequestMapping(value = "/exampleCall",
produces = { "application/json" },
method = RequestMethod.GET)
default ResponseEntity<ExampleResponse> exampleCall() {
return getDelegate().exampleCall();
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试像这样实现委托时
public class ExampleCallApiDelegateImpl implements ExampleCallApiDelegate {
@Override
public ResponseEntity<ExampleResponse> exampleCall() {
ExampleError error = new ExampleError();
error.setCode("123");
return new ResponseEntity<ExampleError>(error, HttpStatus.BAD_REQUEST);
}
}
Run Code Online (Sandbox Code Playgroud)
由于返回类型不正确,它当然无法编译。
使用 Swagger 生成的 API 为每个响应代码实现不同的返回对象的正确方法是什么?还有正确的方法吗?
根据 Swagger 官方文档:
Swagger 是一组围绕 OpenAPI 规范构建的开源工具,可以帮助您设计、构建、记录和使用 REST API。
代表性状态转移架构风格强制执行一组多个约束。其中之一是拥有统一的接口,它本身涉及几个其他约束,特别是通过有效服务器数据的表示进行资源操作。
Swagger 的构建方式是最好地强制执行构建 REST API 的这些约束,如果原始请求是从原始请求创建、读取、修改或抑制原始资源,则如果 API 返回另一个资源的表示,则会违反 REST 原则服务器。
因此,在 Swagger 生成的 REST API 中,没有正确的方法为不同的响应代码返回不同的对象。
| 归档时间: |
|
| 查看次数: |
1291 次 |
| 最近记录: |