如何在 Java 中重新抛出异常

问题描述

我正在使用 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",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 似乎也没有更正响应类型。

如本问题所述, How to handle multiple response/return types (empty for 204,non-empty for 400 etc) in swagger codegen?

我可以这样扔

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

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

非常感谢。

解决方法

您可以像这样在 throws 声明中添加 ApiException

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

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

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