Add detailed 404 error logging for invalid requests

- Log invalid request method, URL, path, and parameters
- Display query parameters and request body if present
- Show client IP and User-Agent information
- Return helpful error message with available endpoints
- Format console output with clear visual separators
This commit is contained in:
1e0n
2025-10-07 01:53:27 +08:00
parent ad862f73d1
commit 1bfbf5a31c

View File

@@ -34,6 +34,64 @@ app.get('/', (req, res) => {
});
});
// 404 处理 - 捕获所有未匹配的路由
app.use((req, res, next) => {
const errorInfo = {
timestamp: new Date().toISOString(),
method: req.method,
url: req.originalUrl || req.url,
path: req.path,
query: req.query,
params: req.params,
body: req.body,
headers: {
'content-type': req.headers['content-type'],
'user-agent': req.headers['user-agent'],
'origin': req.headers['origin'],
'referer': req.headers['referer']
},
ip: req.ip || req.connection.remoteAddress
};
console.error('\n' + '='.repeat(80));
console.error('❌ 非法请求地址');
console.error('='.repeat(80));
console.error(`时间: ${errorInfo.timestamp}`);
console.error(`方法: ${errorInfo.method}`);
console.error(`地址: ${errorInfo.url}`);
console.error(`路径: ${errorInfo.path}`);
if (Object.keys(errorInfo.query).length > 0) {
console.error(`查询参数: ${JSON.stringify(errorInfo.query, null, 2)}`);
}
if (errorInfo.body && Object.keys(errorInfo.body).length > 0) {
console.error(`请求体: ${JSON.stringify(errorInfo.body, null, 2)}`);
}
console.error(`客户端IP: ${errorInfo.ip}`);
console.error(`User-Agent: ${errorInfo.headers['user-agent'] || 'N/A'}`);
if (errorInfo.headers.referer) {
console.error(`来源: ${errorInfo.headers.referer}`);
}
console.error('='.repeat(80) + '\n');
logError('Invalid request path', errorInfo);
res.status(404).json({
error: 'Not Found',
message: `路径 ${req.method} ${req.path} 不存在`,
timestamp: errorInfo.timestamp,
availableEndpoints: [
'GET /v1/models',
'POST /v1/chat/completions'
]
});
});
// 错误处理中间件
app.use((err, req, res, next) => {
logError('Unhandled error', err);
res.status(500).json({