在Ubuntu系統中使用Swagger處理API錯誤,可按以下步驟操作:
components/schemas
中定義錯誤響應模型,包含錯誤碼、消息等字段。components:
schemas:
ErrorResponse:
type: object
properties:
code: { type: integer }
message: { type: string }
responses
中引用錯誤模型,指定HTTP狀態碼及對應的錯誤模型。paths:
/example:
get:
responses:
'400':
description: Bad Request
content:
application/json:
schema: { $ref: '#/components/schemas/ErrorResponse' }
app.get('/example', (req, res) => {
try {
// 業務邏輯
} catch (error) {
res.status(500).json({ code: 500, message: 'Internal Server Error' });
}
});
可進一步集成日志記錄(如使用Winston)監控錯誤,或通過全局異常處理器統一處理錯誤。