在Linux環境下,使用Swagger進行錯誤處理通常涉及以下幾個步驟:
定義錯誤模型:
components:
schemas:
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
在API端點中返回錯誤響應:
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.get('/example', (req, res) => {
try {
// Your logic here
res.json({ message: 'Success' });
} catch (error) {
res.status(500).json({
code: 500,
message: 'Internal Server Error',
details: [{ field: 'example', message: error.message }]
});
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
配置Swagger UI:
paths:
/example:
get:
summary: Example endpoint
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: object
properties:
message:
type: string
'500':
description: Internal Server Error
content:
application/json:
schema:
$ref: '#/components/schemas/ErrorResponse'
測試錯誤處理:
通過以上步驟,你可以在Linux環境下使用Swagger進行有效的錯誤處理。確保你的錯誤模型清晰定義,并在API端點中正確返回錯誤響應,這樣Swagger UI和其他客戶端就能正確理解和顯示這些錯誤信息。