故障排除指南
概览
创建结构化的故障排除文档,帮助用户和支持团队快速诊断和解决常见问题。
何时使用
- 常见问题解答文档
- 常见错误消息
- 调试指南
- 已知问题列表
- 错误代码参考
- 性能故障排除
- 配置问题
- 安装问题
故障排除指南模板
# 故障排除指南
## 快速诊断
### 服务是否正常工作?
首先检查我们的[状态页面](https://status.example.com)。
### 快速健康检查
```bash
# 1. 检查服务是否运行
curl https://api.example.com/health
# 2. 检查您的API密钥
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://api.example.com/api/v1/status
# 3. 检查网络连接
ping api.example.com
# 4. 检查DNS解析
nslookup api.example.com
常见问题
问题:“认证失败”
错误代码: 401 未授权
错误消息:
{
"error": "认证失败",
"code": "AUTH_001",
"message": "无效或过期的API密钥"
}
可能的原因:
- 无效的API密钥
- 过期的API密钥
- 请求中未包含API密钥
- 错误的认证方法
解决方案:
步骤1:验证API密钥格式
# API密钥应为32个字符,字母数字
# 格式:ak_1234567890abcdef1234567890abcdef
# 检查您的密钥
echo $API_KEY | wc -c # 应为32
步骤2:测试API密钥
curl -H "Authorization: Bearer $API_KEY" \
https://api.example.com/api/v1/auth/verify
# 预期响应:
# {"valid": true, "expires": "2025-12-31T23:59:59Z"}
步骤3:生成新密钥(如有必要)
- 登录到仪表板
- 导航到设置>API密钥
- 点击"生成新密钥"
- 复制并安全保存密钥
- 更新您的应用程序配置
步骤4:验证配置
// ✅ 正确
const response = await fetch('https://api.example.com/api/v1/data', {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
// ❌ 错误 - 缺少Bearer前缀
headers: {
'Authorization': apiKey
}
// ❌ 错误 - 错误的头名称
headers: {
'X-API-Key': apiKey
}
仍然无法工作?
- 检查API密钥是否具有所需的权限
- 验证账户是否活跃且未被暂停
- 检查IP白名单是否配置正确
- 联系支持并提供错误响应中的请求ID
问题:“速率限制超出”
错误代码: 429 太多请求
错误消息:
{
"error": "速率限制超出",
"code": "RATE_001",
"message": "您已超出速率限制",
"limit": 100,
"remaining": 0,
"reset": 1642694400
}
理解速率限制:
| 计划 | 速率限制 | 突发 | 重置周期 |
|---|---|---|---|
| 免费 | 100/小时 | 10/秒 | 1小时 |
| Pro | 1000/小时 | 50/秒 | 1小时 |
| 企业 | 10000/小时 | 100/秒 | 1小时 |
解决方案:
选项1:实现指数退避
async function fetchWithRetry(url, options = {}, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(url, options);
if (response.status === 429) {
const resetTime = response.headers.get('X-RateLimit-Reset');
const waitTime = resetTime
? (resetTime * 1000) - Date.now()
: Math.pow(2, i) * 1000;
console.log(`速率限制。等待${waitTime}ms...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
continue;
}
return response;
} catch (error) {
if (i === maxRetries - 1) throw error;
}
}
}
选项2:检查速率限制头
const response = await fetch('https://api.example.com/api/v1/data', {
headers: { 'Authorization': `Bearer ${apiKey}` }
});
console.log('限制:', response.headers.get('X-RateLimit-Limit'));
console.log('剩余:', response.headers.get('X-RateLimit-Remaining'));
console.log('重置:', response.headers.get('X-RateLimit-Reset'));
选项3:批量请求
// ❌ 不要这样做 - 100个单独请求
for (const id of userIds) {
await fetchUser(id);
}
// ✅ 这样做 - 1个批量请求
await fetchUsers(userIds); // API支持批量获取
选项4:升级计划
- 访问定价
- 升级到更高级别以增加限制
问题:“连接超时”
错误消息:
错误:连接ETIMEDOUT
错误:套接字挂起
可能的原因:
- 网络连接问题
- 防火墙阻止出站连接
- DNS解析失败
- 服务暂时不可用
- 错误的端点URL
诊断步骤:
1. 检查网络连接
# 测试基本连接
ping api.example.com
# 测试HTTPS连接
curl -v https://api.example.com
# 测试超时
curl --max-time 10 https://api.example.com/health
2. 检查DNS解析
# 检查DNS
nslookup api.example.com
# 预期输出:
# 名称:api.example.com
# 地址:93.184.216.34
# 尝试备用DNS
nslookup api.example.com 8.8.8.8
3. 检查防火墙/代理
# 测试是否使用代理
curl -v --proxy http://proxy.example.com:8080 \
https://api.example.com
# 检查端口443是否开放
nc -zv api.example.com 443
4. 从不同网络测试
# 从不同的网络隔离问题
# 尝试移动热点,不同的WiFi等
解决方案:
解决方案1:增加超时
// ✅ 设置合理的超时
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 30000); // 30秒
try {
const response = await fetch('https://api.example.com/api/v1/data', {
signal: controller.signal,
headers: { 'Authorization': `Bearer ${apiKey}` }
});
} finally {
clearTimeout(timeout);
}
解决方案2:配置代理
// Node.js使用代理
const HttpsProxyAgent = require('https-proxy-agent');
const agent = new HttpsProxyAgent('http://proxy.example.com:8080');
fetch('https://api.example.com', { agent });
解决方案3:使用备用端点
# 如果主端点失败,尝试备用
curl https://api-backup.example.com/health
问题:“无效的JSON响应”
错误消息:
SyntaxError: 在JSON的第0位置意外标记<
可能的原因:
- 服务器返回HTML错误页面而不是JSON
- 响应不是有效的JSON
- 空响应体
- 内容类型不匹配
诊断步骤:
1. 检查原始响应
curl -v https://api.example.com/api/v1/data \
-H "Authorization: Bearer $API_KEY"
# 查看:
# - 状态码
# - 内容类型头
# - 响应体
2. 检查内容类型
const response = await fetch('https://api.example.com/api/v1/data');
console.log('内容类型:', response.headers.get('Content-Type'));
// 预期:"application/json"
3. 检查响应体
const response = await fetch('https://api.example.com/api/v1/data');
const text = await response.text();
console.log('原始响应:', text);
// 然后尝试解析
try {
const data = JSON.parse(text);
} catch (error) {
console.error('无效JSON:', error.message);
}
解决方案:
解决方案1:解析前验证
async function fetchJSON(url, options) {
const response = await fetch(url, options);
// 检查状态
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// 检查内容类型
const contentType = response.headers.get('Content-Type');
if (!contentType || !contentType.includes('application/json')) {
const text = await response.text();
throw new Error(`预期JSON但得到:${text.substring(0, 100)}`);
}
// 解析JSON
return response.json();
}
解决方案2:处理空响应
const response = await fetch('https://api.example.com/api/v1/data');
const text = await response.text();
// 处理空响应
if (!text || text.trim() === '') {
return null;
}
return JSON.parse(text);
问题:“性能缓慢”
症状:
- API请求> 5秒
- 超时
- 应用程序感觉迟钝
诊断步骤:
1. 测量请求时间
# 使用curl
time curl https://api.example.com/api/v1/data
# 详细计时
curl -w "@curl-format.txt" -o /dev/null -s \
https://api.example.com/api/v1/data
# curl-format.txt:
# time_namelookup: %{time_namelookup}s
# time_connect: %{time_connect}s
# time_appconnect: %{time_appconnect}s
# time_pretransfer: %{time_pretransfer}s
# time_redirect: %{time_redirect}s
# time_starttransfer: %{time_starttransfer}s
# ----------
# time_total: %{time_total}s
2. 检查响应大小
curl -I https://api.example.com/api/v1/data
# 查看内容长度头
3. 从不同位置测试
# 使用在线工具从不同区域测试
# - https://www.dotcom-tools.com/website-speed-test.aspx
# - https://tools.pingdom.com/
解决方案:
解决方案1:使用分页
// ❌ 一次性获取所有数据
const response = await fetch('/api/v1/users');
const users = await response.json(); // 10,000用户!
// ✅ 获取分页数据
const response = await fetch('/api/v1/users?page=1&limit=50');
const { data, pagination } = await response.json();
解决方案2:使用字段选择
// ❌ 获取所有字段
const response = await fetch('/api/v1/users/123');
// ✅ 仅选择所需字段
const response = await fetch('/api/v1/users/123?fields=id,name,email');
解决方案3:实现缓存
const cache = new Map();
const CACHE_TTL = 5 * 60 * 1000; // 5分钟
async function fetchWithCache(url) {
const cached = cache.get(url);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.data;
}
const response = await fetch(url);
const data = await response.json();
cache.set(url, {
data,
timestamp: Date.now()
});
return data;
}
解决方案4:使用CDN
// 使用CDN端点用于静态资产
const cdnUrl = 'https://cdn.example.com/api/v1/data';
错误代码参考
| 代码 | HTTP | 描述 | 解决方案 |
|---|---|---|---|
| AUTH_001 | 401 | 无效的API密钥 | 重新生成API密钥 |
| AUTH_002 | 401 | 过期的API密钥 | 生成新密钥 |
| AUTH_003 | 403 | 权限不足 | 检查API密钥范围 |
| RATE_001 | 429 | 速率限制超出 | 等待或升级计划 |
| RATE_002 | 429 | 并发请求限制 | 减少并行性 |
| VAL_001 | 400 | 缺少必需字段 | 检查请求正文 |
| VAL_002 | 400 | 字段格式无效 | 验证输入 |
| RES_001 | 404 | 资源未找到 | 检查资源ID |
| RES_002 | 409 | 资源已存在 | 使用更新代替 |
| SRV_001 | 500 | 内部服务器错误 | 联系支持 |
| SRV_002 | 503 | 服务不可用 | 退避重试 |
获取帮助
联系支持前
联系支持时
包括以下内容:
- 错误消息和错误代码
- 请求ID(来自响应头)
- 问题的时间戳
- 被调用的API端点
- 代码片段(不含凭据!)
- 重现步骤
示例支持请求:
主题:/api/v1/users端点上的错误429
嗨,
我在调用/api/v1/users端点时收到429错误。
错误消息:
{
"error": "速率限制超出",
"code": "RATE_001",
"request_id": "req_abc123"
}
细节:
- 时间戳:2025-01-15T14:30:00Z
- 请求ID:req_abc123
- 端点:GET /api/v1/users
- 账户:user@example.com
- 计划:Pro
我每小时只做大约50个请求,应该在限制之内。您能帮忙调查吗?
谢谢!
有用链接
- 文档: https://docs.example.com
- 状态页面: https://status.example.com
- 社区: https://community.example.com
- 支持: support@example.com
- GitHub问题: https://github.com/example/repo/issues
## 最佳实践
### ✅ 做
- 从最常见的问题开始
- 逐字包含错误消息
- 提供逐步诊断
- 显示预期与实际输出
- 包括代码示例
- 记录错误代码
- 添加屏幕截图/视频
- 链接到相关文档
- 保持解决方案最新
- 包括变通方法
- 测试所有解决方案
### ❌ 不做
- 使用模糊描述
- 跳过诊断步骤
- 忘记显示示例
- 假设技术知识
- 跳过验证步骤
- 忘记边缘情况
## 资源
- [Google的技术写作指南](https://developers.google.com/tech-writing)
- [Microsoft故障排除指南](https://docs.microsoft.com/troubleshoot/)
- [Stack Overflow文档](https://stackoverflow.com/documentation)