温馨提示×

Ubuntu Swagger如何处理API错误

小樊
57
2025-08-09 05:08:30
栏目: 智能运维

在Ubuntu系统中使用Swagger处理API错误,可按以下步骤操作:

  1. 定义错误模型:在Swagger文档(YAML/JSON格式)的components/schemas中定义错误响应模型,包含错误码、消息等字段。
    components:  
      schemas:  
        ErrorResponse:  
          type: object  
          properties:  
            code: { type: integer }  
            message: { type: string }  
    
  2. 配置API端点错误响应:在路径操作的responses中引用错误模型,指定HTTP状态码及对应的错误模型。
    paths:  
      /example:  
        get:  
          responses:  
            '400':  
              description: Bad Request  
              content:  
                application/json:  
                  schema: { $ref: '#/components/schemas/ErrorResponse' }  
    
  3. 后端实现错误处理逻辑:在代码中捕获异常,返回符合错误模型的响应。例如,在Express中:
    app.get('/example', (req, res) => {  
      try {  
        // 业务逻辑  
      } catch (error) {  
        res.status(500).json({ code: 500, message: 'Internal Server Error' });  
      }  
    });  
    
  4. 测试与验证:通过Swagger UI或Postman触发错误场景,验证响应是否符合定义的模型。

可进一步集成日志记录(如使用Winston)监控错误,或通过全局异常处理器统一处理错误。

0