linux

Linux下Swagger的错误处理策略

小樊
38
2025-11-26 07:49:24
栏目: 智能运维

Linux下Swagger的错误处理策略

一 策略总览

二 规范定义与文档化

openapi: 3.0.3
info:
  title: 示例 API
  version: 1.0.0
paths:
  /items/{itemId}:
    get:
      summary: 获取指定ID的项目
      parameters:
        - in: path
          name: itemId
          required: true
          schema:
            type: string
      responses:
        '200':
          description: 成功
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Item'
        '404':
          description: 未找到
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
components:
  schemas:
    Item:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
    ErrorResponse:
      type: object
      properties:
        code:
          type: integer
          format: int32
        message:
          type: string
        details:
          type: array
          items:
            type: object
            properties:
              field:
                type: string
              message:
                type: string
@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.example.demo"))
            .paths(PathSelectors.any())
            .build()
            .useDefaultResponseMessages(false)
            .globalResponses(HttpMethod.GET, Arrays.asList(
                    new ResponseBuilder()
                            .code("404")
                            .description("Resource not found")
                            .representation(MediaType.APPLICATION_JSON)
                            .modelRef(new ModelRef("ErrorResponse"))
                            .build()
            ));
}

三 后端实现与统一异常处理

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
        ErrorResponse err = new ErrorResponse();
        err.setCode(HttpStatus.NOT_FOUND.value());
        err.setMessage(ex.getMessage());
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(err);
    }

    // 其他异常:IllegalArgumentException、ValidationException、Exception
}
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

app.get('/example', (req, res) => {
  try {
    // 业务逻辑
    res.json({ data: 'ok' });
  } catch (err) {
    // 统一错误响应
    res.status(500).json({
      code: 500,
      message: 'Internal Server Error',
      details: [{ field: 'example', message: err.message }]
    });
  }
});

四 部署连通性与Swagger UI问题排查

@Bean
public Docket api() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .pathMapping("/api-docs");
}

五 日志监控与可观测性

logging.level.root=INFO
logging.level.com.example.demo=DEBUG
logging.file.name=app.log
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} - %msg%n

0
看了该问题的人还看了