refactor: 系统优化 - 错误处理、输入验证、无限滚动
主要改进: - 新增配置管理 (server/config.js) - 新增日志工具 (server/utils/logger.js) - 添加全局错误处理中间件,统一错误响应格式 - 添加输入验证和 AppError 错误类 - 重构 db.js 迁移逻辑,代码更清晰 - 前端列表改为无限滚动加载,每页 20 条 - 封装 AppState 状态管理模块 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 4.6
parent
19e5a48f07
commit
d551841035
+35
-3
@@ -3,6 +3,8 @@ const cors = require('cors');
|
||||
const path = require('path');
|
||||
const compression = require('compression');
|
||||
|
||||
const config = require('./config');
|
||||
const logger = require('./utils/logger');
|
||||
const db = require('./db');
|
||||
const { router: authRouter, auth } = require('./routes/auth');
|
||||
const statsRouter = require('./routes/stats');
|
||||
@@ -11,6 +13,9 @@ const ioRouter = require('./routes/io');
|
||||
|
||||
const app = express();
|
||||
|
||||
// 请求日志中间件
|
||||
app.use(logger.requestLogger);
|
||||
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(compression());
|
||||
@@ -44,7 +49,34 @@ app.use('/api/stats', auth, statsRouter);
|
||||
app.use('/api/records', auth, recordsRouter);
|
||||
app.use('/api', auth, ioRouter);
|
||||
|
||||
const PORT = process.env.PORT || 3000;
|
||||
app.listen(PORT, '0.0.0.0', () => {
|
||||
console.log(`服务器运行在 http://0.0.0.0:${PORT}`);
|
||||
// 404 处理
|
||||
app.use((req, res) => {
|
||||
res.status(404).json({ error: '接口不存在' });
|
||||
});
|
||||
|
||||
// 全局错误处理中间件
|
||||
app.use((err, req, res, next) => {
|
||||
// 记录错误日志
|
||||
logger.error('Unhandled error:', err.message, err.stack);
|
||||
|
||||
// 处理特定错误类型
|
||||
if (err.name === 'UnauthorizedError') {
|
||||
return res.status(401).json({ error: '未授权访问' });
|
||||
}
|
||||
|
||||
if (err.name === 'SyntaxError' && err.status === 400 && 'body' in err) {
|
||||
return res.status(400).json({ error: 'JSON 格式错误' });
|
||||
}
|
||||
|
||||
// 默认错误响应
|
||||
const status = err.status || err.statusCode || 500;
|
||||
const message = err.expose ? err.message : '服务器内部错误';
|
||||
|
||||
res.status(status).json({ error: message });
|
||||
});
|
||||
|
||||
const PORT = config.port;
|
||||
const HOST = config.host;
|
||||
app.listen(PORT, HOST, () => {
|
||||
logger.info(`服务器运行在 http://${HOST}:${PORT}`);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user