溫馨提示×

Ubuntu Swagger如何處理API錯誤

小樊
41
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女