troubleshooting-guide
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTroubleshooting Guide
故障排查指南
Overview
概述
Create structured troubleshooting documentation that helps users and support teams quickly diagnose and resolve common issues.
创建结构化的故障排查文档,帮助用户和支持团队快速诊断并解决常见问题。
When to Use
适用场景
- FAQ documentation
- Common error messages
- Debug guides
- Known issues lists
- Error code reference
- Performance troubleshooting
- Configuration issues
- Installation problems
- FAQ文档
- 常见错误信息
- 调试指南
- 已知问题列表
- 错误码参考
- 性能故障排查
- 配置问题
- 安装问题
Troubleshooting Guide Template
故障排查指南模板
markdown
undefinedmarkdown
undefinedTroubleshooting Guide
故障排查指南
Quick Diagnosis
快速诊断
Is the Service Working?
服务是否正常运行?
Check our Status Page first.
请首先查看我们的状态页面。
Quick Health Checks
快速健康检查
bash
undefinedbash
undefined1. Check service is running
1. 检查服务是否运行
2. Check your API key
2. 检查你的API key
curl -H "Authorization: Bearer YOUR_API_KEY"
https://api.example.com/api/v1/status
https://api.example.com/api/v1/status
curl -H "Authorization: Bearer YOUR_API_KEY"
https://api.example.com/api/v1/status
https://api.example.com/api/v1/status
3. Check network connectivity
3. 检查网络连通性
ping api.example.com
ping api.example.com
4. Check DNS resolution
4. 检查DNS解析
nslookup api.example.com
undefinednslookup api.example.com
undefinedCommon Issues
常见问题
Issue: "Authentication Failed"
问题: "Authentication Failed"
Error Code:
401 UnauthorizedError Message:
json
{
"error": "Authentication failed",
"code": "AUTH_001",
"message": "Invalid or expired API key"
}Possible Causes:
- Invalid API key
- Expired API key
- API key not included in request
- Wrong authentication method
Solution:
Step 1: Verify API Key Format
bash
undefined错误码:
401 Unauthorized错误消息:
json
{
"error": "Authentication failed",
"code": "AUTH_001",
"message": "Invalid or expired API key"
}可能原因:
- 无效的API key
- 过期的API key
- 请求中未包含API key
- 身份验证方式错误
解决方案:
步骤1: 验证API key格式
bash
undefinedAPI keys should be 32 characters, alphanumeric
API key应为32位字母数字组合
Format: ak_1234567890abcdef1234567890abcdef
格式: ak_1234567890abcdef1234567890abcdef
Check your key
检查你的key
echo $API_KEY | wc -c # Should be 32
**Step 2: Test API Key**
```bash
curl -H "Authorization: Bearer $API_KEY" \
https://api.example.com/api/v1/auth/verifyecho $API_KEY | wc -c # 应为32
**步骤2: 测试API key**
```bash
curl -H "Authorization: Bearer $API_KEY" \
https://api.example.com/api/v1/auth/verifyExpected response:
预期响应:
{"valid": true, "expires": "2025-12-31T23:59:59Z"}
{"valid": true, "expires": "2025-12-31T23:59:59Z"}
**Step 3: Generate New Key (if needed)**
1. Log in to [Dashboard](https://dashboard.example.com)
2. Navigate to Settings > API Keys
3. Click "Generate New Key"
4. Copy and save the key securely
5. Update your application configuration
**Step 4: Verify Configuration**
```javascript
// ✅ Correct
const response = await fetch('https://api.example.com/api/v1/data', {
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
});
// ❌ Incorrect - missing Bearer prefix
headers: {
'Authorization': apiKey
}
// ❌ Incorrect - wrong header name
headers: {
'X-API-Key': apiKey
}Still Not Working?
- Check if API key has required permissions
- Verify account is active and not suspended
- Check if IP whitelist is configured correctly
- Contact support with request ID from error response
**步骤3: 生成新的key(如有需要)**
1. 登录[控制台](https://dashboard.example.com)
2. 导航至 设置 > API Keys
3. 点击 "Generate New Key"
4. 安全地复制并保存新key
5. 更新应用配置
**步骤4: 验证配置**
```javascript
// ✅ 正确写法
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 key是否拥有所需权限
- 验证账户是否处于活跃状态且未被暂停
- 检查IP白名单配置是否正确
- 联系支持团队,并提供错误响应中的请求ID
Issue: "Rate Limit Exceeded"
问题: "Rate Limit Exceeded"
Error Code:
429 Too Many RequestsError Message:
json
{
"error": "Rate limit exceeded",
"code": "RATE_001",
"message": "You have exceeded the rate limit",
"limit": 100,
"remaining": 0,
"reset": 1642694400
}Understanding Rate Limits:
| Plan | Rate Limit | Burst | Reset Period |
|---|---|---|---|
| Free | 100/hour | 10/second | 1 hour |
| Pro | 1000/hour | 50/second | 1 hour |
| Enterprise | 10000/hour | 100/second | 1 hour |
Solutions:
Option 1: Implement Exponential Backoff
javascript
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(`Rate limited. Waiting ${waitTime}ms...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
continue;
}
return response;
} catch (error) {
if (i === maxRetries - 1) throw error;
}
}
}Option 2: Check Rate Limit Headers
javascript
const response = await fetch('https://api.example.com/api/v1/data', {
headers: { 'Authorization': `Bearer ${apiKey}` }
});
console.log('Limit:', response.headers.get('X-RateLimit-Limit'));
console.log('Remaining:', response.headers.get('X-RateLimit-Remaining'));
console.log('Reset:', response.headers.get('X-RateLimit-Reset'));Option 3: Batch Requests
javascript
// ❌ Don't do this - 100 separate requests
for (const id of userIds) {
await fetchUser(id);
}
// ✅ Do this - 1 batch request
await fetchUsers(userIds); // API supports bulk fetchOption 4: Upgrade Plan
- Visit Pricing
- Upgrade to higher tier for increased limits
错误码:
429 Too Many Requests错误消息:
json
{
"error": "Rate limit exceeded",
"code": "RATE_001",
"message": "You have exceeded the rate limit",
"limit": 100,
"remaining": 0,
"reset": 1642694400
}Rate Limit说明:
| 套餐 | Rate Limit | 突发请求数 | 重置周期 |
|---|---|---|---|
| 免费版 | 100/小时 | 10/秒 | 1小时 |
| 专业版 | 1000/小时 | 50/秒 | 1小时 |
| 企业版 | 10000/小时 | 100/秒 | 1小时 |
解决方案:
选项1: 实现指数退避算法
javascript
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(`Rate limited. Waiting ${waitTime}ms...`);
await new Promise(resolve => setTimeout(resolve, waitTime));
continue;
}
return response;
} catch (error) {
if (i === maxRetries - 1) throw error;
}
}
}选项2: 检查Rate Limit头部信息
javascript
const response = await fetch('https://api.example.com/api/v1/data', {
headers: { 'Authorization': `Bearer ${apiKey}` }
});
console.log('Limit:', response.headers.get('X-RateLimit-Limit'));
console.log('Remaining:', response.headers.get('X-RateLimit-Remaining'));
console.log('Reset:', response.headers.get('X-RateLimit-Reset'));选项3: 批量请求
javascript
// ❌ 不推荐 - 100次独立请求
for (const id of userIds) {
await fetchUser(id);
}
// ✅ 推荐 - 1次批量请求
await fetchUsers(userIds); // API支持批量获取选项4: 升级套餐
- 访问定价页面
- 升级至更高套餐以获得更高的限制
Issue: "Connection Timeout"
问题: "Connection Timeout"
Error Message:
Error: connect ETIMEDOUT
Error: socket hang upPossible Causes:
- Network connectivity issues
- Firewall blocking outbound connections
- DNS resolution failure
- Service temporarily unavailable
- Incorrect endpoint URL
Diagnostic Steps:
1. Check Network Connectivity
bash
undefined错误消息:
Error: connect ETIMEDOUT
Error: socket hang up可能原因:
- 网络连通性问题
- 防火墙阻止出站连接
- DNS解析失败
- 服务暂时不可用
- 端点URL错误
诊断步骤:
1. 检查网络连通性
bash
undefinedTest basic connectivity
测试基础连通性
ping api.example.com
ping api.example.com
Test HTTPS connectivity
测试HTTPS连通性
curl -v https://api.example.com
curl -v https://api.example.com
Test with timeout
带超时测试
curl --max-time 10 https://api.example.com/health
**2. Check DNS Resolution**
```bashcurl --max-time 10 https://api.example.com/health
**2. 检查DNS解析**
```bashCheck DNS
检查DNS
nslookup api.example.com
nslookup api.example.com
Expected output:
预期输出:
Name: api.example.com
Name: api.example.com
Address: 93.184.216.34
Address: 93.184.216.34
Try alternative DNS
尝试备用DNS
nslookup api.example.com 8.8.8.8
**3. Check Firewall/Proxy**
```bashnslookup api.example.com 8.8.8.8
**3. 检查防火墙/代理**
```bashTest if using proxy
测试是否使用代理
Check if port 443 is open
检查443端口是否开放
nc -zv api.example.com 443
**4. Test from Different Network**
```bashnc -zv api.example.com 443
**4. 在不同网络测试**
```bashTest from different network to isolate issue
在不同网络测试以隔离问题
Try mobile hotspot, different WiFi, etc.
尝试移动热点、其他WiFi等
**Solutions:**
**Solution 1: Increase Timeout**
```javascript
// ✅ Set reasonable timeout
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 30000); // 30 seconds
try {
const response = await fetch('https://api.example.com/api/v1/data', {
signal: controller.signal,
headers: { 'Authorization': `Bearer ${apiKey}` }
});
} finally {
clearTimeout(timeout);
}Solution 2: Configure Proxy
javascript
// Node.js with proxy
const HttpsProxyAgent = require('https-proxy-agent');
const agent = new HttpsProxyAgent('http://proxy.example.com:8080');
fetch('https://api.example.com', { agent });Solution 3: Use Alternative Endpoint
bash
undefined
**解决方案:**
**方案1: 增加超时时间**
```javascript
// ✅ 设置合理的超时时间
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: 配置代理
javascript
// Node.js环境下配置代理
const HttpsProxyAgent = require('https-proxy-agent');
const agent = new HttpsProxyAgent('http://proxy.example.com:8080');
fetch('https://api.example.com', { agent });方案3: 使用备用端点
bash
undefinedIf primary endpoint fails, try alternative
如果主端点失败,尝试备用端点
Issue: "Invalid JSON Response"
问题: "Invalid JSON Response"
Error Message:
SyntaxError: Unexpected token < in JSON at position 0Possible Causes:
- Server returned HTML error page instead of JSON
- Response is not valid JSON
- Empty response body
- Content-Type mismatch
Diagnostic Steps:
1. Inspect Raw Response
bash
curl -v https://api.example.com/api/v1/data \
-H "Authorization: Bearer $API_KEY"错误消息:
SyntaxError: Unexpected token < in JSON at position 0可能原因:
- 服务器返回HTML错误页面而非JSON
- 响应不是有效的JSON
- 响应体为空
- Content-Type不匹配
诊断步骤:
1. 检查原始响应
bash
curl -v https://api.example.com/api/v1/data \
-H "Authorization: Bearer $API_KEY"Look at:
检查:
- Status code
- 状态码
- Content-Type header
- Content-Type头部
- Response body
- 响应体
**2. Check Content-Type**
```javascript
const response = await fetch('https://api.example.com/api/v1/data');
console.log('Content-Type:', response.headers.get('Content-Type'));
// Expected: "application/json"3. Check Response Body
javascript
const response = await fetch('https://api.example.com/api/v1/data');
const text = await response.text();
console.log('Raw response:', text);
// Then try to parse
try {
const data = JSON.parse(text);
} catch (error) {
console.error('Invalid JSON:', error.message);
}Solutions:
Solution 1: Validate Before Parsing
javascript
async function fetchJSON(url, options) {
const response = await fetch(url, options);
// Check status
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// Check content type
const contentType = response.headers.get('Content-Type');
if (!contentType || !contentType.includes('application/json')) {
const text = await response.text();
throw new Error(`Expected JSON but got: ${text.substring(0, 100)}`);
}
// Parse JSON
return response.json();
}Solution 2: Handle Empty Responses
javascript
const response = await fetch('https://api.example.com/api/v1/data');
const text = await response.text();
// Handle empty response
if (!text || text.trim() === '') {
return null;
}
return JSON.parse(text);
**2. 检查Content-Type**
```javascript
const response = await fetch('https://api.example.com/api/v1/data');
console.log('Content-Type:', response.headers.get('Content-Type'));
// 预期值: "application/json"3. 检查响应体
javascript
const response = await fetch('https://api.example.com/api/v1/data');
const text = await response.text();
console.log('原始响应:', text);Issue: "Slow Performance"
然后尝试解析
Symptoms:
- API requests taking > 5 seconds
- Timeouts
- Application feels sluggish
Diagnostic Steps:
1. Measure Request Time
bash
undefinedtry {
const data = JSON.parse(text);
} catch (error) {
console.error('无效JSON:', error.message);
}
**解决方案:**
**方案1: 解析前验证**
```javascript
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: 处理空响应
javascript
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);Using curl
问题: "Slow Performance"
time curl https://api.example.com/api/v1/data
症状:
- API请求耗时超过5秒
- 请求超时
- 应用响应缓慢
诊断步骤:
1. 测量请求时间
bash
undefinedDetailed timing
使用curl测量
curl -w "@curl-format.txt" -o /dev/null -s
https://api.example.com/api/v1/data
https://api.example.com/api/v1/data
time curl https://api.example.com/api/v1/data
curl-format.txt:
详细计时
time_namelookup: %{time_namelookup}s\n
—
time_connect: %{time_connect}s\n
—
time_appconnect: %{time_appconnect}s\n
—
time_pretransfer: %{time_pretransfer}s\n
—
time_redirect: %{time_redirect}s\n
—
time_starttransfer: %{time_starttransfer}s\n
—
----------\n
—
time_total: %{time_total}s\n
—
**2. Check Response Size**
```bash
curl -I https://api.example.com/api/v1/datacurl -w "@curl-format.txt" -o /dev/null -s
https://api.example.com/api/v1/data
https://api.example.com/api/v1/data
Look at Content-Length header
curl-format.txt:
—
time_namelookup: %{time_namelookup}s\n
—
time_connect: %{time_connect}s\n
—
time_appconnect: %{time_appconnect}s\n
—
time_pretransfer: %{time_pretransfer}s\n
—
time_redirect: %{time_redirect}s\n
—
time_starttransfer: %{time_starttransfer}s\n
—
----------\n
—
time_total: %{time_total}s\n
**3. Test from Different Locations**
```bash
**2. 检查响应大小**
```bash
curl -I https://api.example.com/api/v1/dataUse online tools to test from different regions
查看Content-Length头部
**Solutions:**
**Solution 1: Use Pagination**
```javascript
// ❌ Fetching all data at once
const response = await fetch('/api/v1/users');
const users = await response.json(); // 10,000 users!
// ✅ Fetch paginated data
const response = await fetch('/api/v1/users?page=1&limit=50');
const { data, pagination } = await response.json();Solution 2: Use Field Selection
javascript
// ❌ Fetching all fields
const response = await fetch('/api/v1/users/123');
// ✅ Select only needed fields
const response = await fetch('/api/v1/users/123?fields=id,name,email');Solution 3: Implement Caching
javascript
const cache = new Map();
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
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;
}Solution 4: Use CDN
javascript
// Use CDN endpoint for static assets
const cdnUrl = 'https://cdn.example.com/api/v1/data';
**3. 在不同位置测试**
```bashError Code Reference
使用在线工具在不同地区测试
| Code | HTTP | Description | Solution |
|---|---|---|---|
| AUTH_001 | 401 | Invalid API key | Regenerate API key |
| AUTH_002 | 401 | Expired API key | Generate new key |
| AUTH_003 | 403 | Insufficient permissions | Check API key scopes |
| RATE_001 | 429 | Rate limit exceeded | Wait or upgrade plan |
| RATE_002 | 429 | Concurrent request limit | Reduce parallelism |
| VAL_001 | 400 | Missing required field | Check request body |
| VAL_002 | 400 | Invalid field format | Validate input |
| RES_001 | 404 | Resource not found | Check resource ID |
| RES_002 | 409 | Resource already exists | Use update instead |
| SRV_001 | 500 | Internal server error | Contact support |
| SRV_002 | 503 | Service unavailable | Retry with backoff |
**解决方案:**
**方案1: 使用分页**
```javascript
// ❌ 一次性获取所有数据
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: 字段选择
javascript
// ❌ 获取所有字段
const response = await fetch('/api/v1/users/123');
// ✅ 仅选择需要的字段
const response = await fetch('/api/v1/users/123?fields=id,name,email');方案3: 实现缓存
javascript
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
javascript
// 使用CDN端点获取静态资源
const cdnUrl = 'https://cdn.example.com/api/v1/data';Getting Help
错误码参考
Before Contacting Support
—
- Check Status Page
- Search Documentation
- Check Community Forum
- Review this troubleshooting guide
| 代码 | HTTP状态码 | 描述 | 解决方案 |
|---|---|---|---|
| AUTH_001 | 401 | 无效的API key | 重新生成API key |
| AUTH_002 | 401 | 过期的API key | 生成新的API key |
| AUTH_003 | 403 | 权限不足 | 检查API key的权限范围 |
| RATE_001 | 429 | Rate Limit超出 | 等待或升级套餐 |
| RATE_002 | 429 | 并发请求数超出 | 减少并行请求数 |
| VAL_001 | 400 | 缺少必填字段 | 检查请求体 |
| VAL_002 | 400 | 字段格式无效 | 验证输入内容 |
| RES_001 | 404 | 资源不存在 | 检查资源ID |
| RES_002 | 409 | 资源已存在 | 使用更新操作替代 |
| SRV_001 | 500 | 服务器内部错误 | 联系支持团队 |
| SRV_002 | 503 | 服务不可用 | 使用退避算法重试 |
When Contacting Support
获取帮助
—
联系支持团队前
Include the following:
- Error message and error code
- Request ID (from response headers)
- Timestamp of the issue
- API endpoint being called
- Code snippet (without credentials!)
- Steps to reproduce
Example Support Request:
Subject: Error 429 on /api/v1/users endpoint
Hi,
I'm getting a 429 error when calling the /api/v1/users endpoint.
Error message:
{
"error": "Rate limit exceeded",
"code": "RATE_001",
"request_id": "req_abc123"
}
Details:
- Timestamp: 2025-01-15T14:30:00Z
- Request ID: req_abc123
- Endpoint: GET /api/v1/users
- Account: user@example.com
- Plan: Pro
I'm only making ~50 requests per hour, which should be within
the limit. Can you help investigate?
Thanks!Useful Links
联系支持团队时
- Documentation: https://docs.example.com
- Status Page: https://status.example.com
- Community: https://community.example.com
- Support: support@example.com
- GitHub Issues: https://github.com/example/repo/issues
undefined请提供以下信息:
- 错误消息和错误码
- 响应头部中的请求ID
- 问题发生的时间戳
- 调用的API端点
- 代码片段(请勿包含凭证信息!)
- 复现步骤
支持请求示例:
主题: /api/v1/users端点出现429错误
您好,
我在调用/api/v1/users端点时收到429错误。
错误消息:
{
"error": "Rate limit exceeded",
"code": "RATE_001",
"request_id": "req_abc123"
}
详细信息:
- 时间戳: 2025-01-15T14:30:00Z
- 请求ID: req_abc123
- 端点: GET /api/v1/users
- 账户: user@example.com
- 套餐: 专业版
我每小时仅发送约50次请求,应该在限制范围内。能否帮忙排查?
谢谢!Best Practices
有用链接
✅ DO
—
- Start with most common issues
- Include error messages verbatim
- Provide step-by-step diagnostics
- Show expected vs actual output
- Include code examples
- Document error codes
- Add screenshots/videos
- Link to related documentation
- Keep solutions up-to-date
- Include workarounds
- Test all solutions
- 文档: https://docs.example.com
- 状态页面: https://status.example.com
- 社区: https://community.example.com
- 支持邮箱: support@example.com
- GitHub Issues: https://github.com/example/repo/issues
undefined❌ DON'T
最佳实践
—
✅ 建议
- Use vague descriptions
- Skip diagnostic steps
- Forget to show examples
- Assume technical knowledge
- Skip verification steps
- Forget edge cases
- 从最常见的问题入手
- 逐字记录错误信息
- 提供分步诊断流程
- 展示预期与实际输出对比
- 包含代码示例
- 记录错误码
- 添加截图/视频
- 链接到相关文档
- 及时更新解决方案
- 提供临时解决方法
- 测试所有解决方案
Resources
❌ 避免
- 使用模糊描述
- 跳过诊断步骤
- 不提供示例
- 假设用户具备专业技术知识
- 跳过验证步骤
- 忽略边缘情况
—