1

我正在使用 maven codegen 插件生成具有如下模式的控制器接口

    responses:
        '200':
            content:
                application/json:
                    schema:
                        $ref: '#/components/schemas/MyResponse'
            description: OK
        '401':
            content:
                application/json:
                    schema:
                        $ref: '#/components/schemas/MyError'

界面如下

    @ApiResponses(value = { 
        @ApiResponse(responseCode = "200", description = "Authentication succeeded", content = @Content(mediaType = "application/json", schema = @Schema(implementation = MyResponse.class))),
        
        @ApiResponse(responseCode = "401", description = "Authentication failed", content = @Content(mediaType = "application/json", schema = @Schema(implementation = MyError.class))) })
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    default ResponseEntity<MyResponse> LoginMethod(//some parameters...) { //something}

在我的控制器中,我想调用一个引发 API 异常的外部 API

    public ResponseEntity<MyResponse> LoginMethod(//some parameters...) {
try { 
  //call external API which throw an exception 
} catch(ApiException e){
  e.getResponseBody; // This is a string type of MyError class in JSON format returned
  // throw e;
}

我想重定向响应正文,但接口将返回类型定义为 ResponseEntity,因此我不能简单地重新抛出异常或返回 ResponseEntity。

@ApiResponse 似乎也没有更正响应类型。

如本问题所述, 如何在 swagger codegen 中处理多种响应/返回类型(204 为空,400 为非空等)?

我可以这样扔

throw new ResponseStatusException(HttpStatus.valueOf(e.getCode()), e.getResponseBody());

但是有没有更好的方法来做到这一点?我只想将 e.getResponseBody() 作为对象而不是字符串返回。

非常感谢。

4

1 回答 1

1

您可以ApiException像这样添加 in throws 声明:

public ResponseEntity<MyResponse> LoginMethod(//some parameters...) throws ApiException {
   // here your code that can create teh ApiException
}

现在调用它的方法也会要求抛出异常。您将能够在其中管理异常。

您还可以创建一个新对象,其中包含您需要的所有信息。它还将格式化信息始终相同,而不取决于抛出的错误。

于 2021-07-30T06:39:46.167 回答