You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Gradle Spring的OpenAPI生成控制器中获取Bad Request响应信息

解决方案

1. 调整OpenAPI Generator配置,启用自动异常处理

在你的生成配置选项中添加useControllerAdvice: "true"参数,这个配置会让代码生成器自动创建全局异常处理类,捕获并格式化MissingServletRequestParameterException这类请求参数异常,将详细错误信息返回至响应体。

修改后的生成配置如下:

{
    "dateLibrary": "java8",
    "hideGenerationTimestamp": "true",
    "delegatePattern": "true",
    "library": "spring-boot",
    "serializableModel": "true",
    "useBeanValidation": "true",
    "useTags": "true",
    "implicitHeaders": "true",
    "openApiNullable": "false",
    "useControllerAdvice": "true"
}

2. 确认生成的全局异常处理类

配置生效后,生成器会在代码中生成类似GlobalExceptionHandler的类,其中包含针对MissingServletRequestParameterException的处理逻辑,示例如下:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<Problem> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, WebRequest request) {
        Problem problem = new Problem();
        problem.setStatus(HttpStatus.BAD_REQUEST.value());
        problem.setTitle("Bad Request");
        problem.setDetail(ex.getMessage());
        problem.setInstance(request.getDescription(false).replace("uri=", ""));
        return new ResponseEntity<>(problem, HttpStatus.BAD_REQUEST);
    }

    // 其他异常处理方法...
}

此时再发送缺失fromDate的请求,响应体就会包含detail字段,内容为Required request parameter 'fromDate' for method parameter type String is not present,满足需求。

3. 自定义错误响应结构(可选)

如果默认生成的Problem类不符合你的响应格式要求,可以通过OpenAPI规范自定义错误模型。

首先在OpenAPI文件中定义错误响应结构:

components:
  schemas:
    CustomErrorResponse:
      type: object
      properties:
        timestamp:
          type: string
          format: date-time
        status:
          type: integer
        error:
          type: string
        message:
          type: string
        path:
          type: string

然后在生成配置中添加errorModel: "CustomErrorResponse",生成器会用你定义的模型来构建异常响应内容。


内容的提问来源于stack exchange,提问作者Thisun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 19:20:29