在Debian系统上,使用Swagger进行API文档编写和错误处理时,可以遵循以下步骤:
sudo apt-get update
sudo apt-get install swagger-ui-express
app.js
的文件,并添加以下内容:const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const app = express();
// 读取Swagger文档
const swaggerDocument = YAML.load('./swagger.yaml');
// 使用swagger-ui-express中间件
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// 启动服务器
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
swagger.yaml
的文件,并添加API文档信息。例如:swagger: '2.0'
info:
title: Sample API
description: A sample API to demonstrate Swagger error handling on Debian.
version: '1.0.0'
host: localhost:3000
basePath: /api
schemes:
- http
paths:
/users:
get:
summary: List all users
responses:
'200':
description: An array of users
schema:
type: array
items:
$ref: '#/definitions/User'
'400':
description: Invalid request
'500':
description: Internal server error
definitions:
User:
type: object
properties:
id:
type: integer
name:
type: string
errorHandler.js
的文件,并添加以下内容:function errorHandler(err, req, res, next) {
console.error(err.stack);
const status = err.status || 500;
const message = err.message || 'Internal Server Error';
res.status(status).json({
error: {
status,
message,
},
});
}
module.exports = errorHandler;
然后,在app.js
文件中引入并使用这个中间件:
const errorHandler = require('./errorHandler');
// ...
// 在所有路由之后添加错误处理中间件
app.use(errorHandler);
// ...
node app.js
现在,可以在浏览器中访问http://localhost:3000/api-docs
查看Swagger文档。如果发生错误,应用将返回相应的错误信息和状态码。