在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)监控错误,或通过全局异常处理器统一处理错误。