troubleshooting-guide

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Troubleshooting 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
undefined
markdown
undefined

Troubleshooting Guide

故障排查指南

Quick Diagnosis

快速诊断

Is the Service Working?

服务是否正常运行?

Check our Status Page first.
请首先查看我们的状态页面

Quick Health Checks

快速健康检查

bash
undefined
bash
undefined

1. 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
curl -H "Authorization: Bearer YOUR_API_KEY"
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
undefined
nslookup api.example.com
undefined

Common Issues

常见问题

Issue: "Authentication Failed"

问题: "Authentication Failed"

Error Code:
401 Unauthorized
Error Message:
json
{
  "error": "Authentication failed",
  "code": "AUTH_001",
  "message": "Invalid or expired API key"
}
Possible Causes:
  1. Invalid API key
  2. Expired API key
  3. API key not included in request
  4. 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"
}
可能原因:
  1. 无效的API key
  2. 过期的API key
  3. 请求中未包含API key
  4. 身份验证方式错误
解决方案:
步骤1: 验证API key格式
bash
undefined

API 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/verify
echo $API_KEY | wc -c # 应为32

**步骤2: 测试API key**
```bash
curl -H "Authorization: Bearer $API_KEY" \
  https://api.example.com/api/v1/auth/verify

Expected 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 Requests
Error 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:
PlanRate LimitBurstReset Period
Free100/hour10/second1 hour
Pro1000/hour50/second1 hour
Enterprise10000/hour100/second1 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 fetch
Option 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 up
Possible Causes:
  1. Network connectivity issues
  2. Firewall blocking outbound connections
  3. DNS resolution failure
  4. Service temporarily unavailable
  5. Incorrect endpoint URL
Diagnostic Steps:
1. Check Network Connectivity
bash
undefined
错误消息:
Error: connect ETIMEDOUT
Error: socket hang up
可能原因:
  1. 网络连通性问题
  2. 防火墙阻止出站连接
  3. DNS解析失败
  4. 服务暂时不可用
  5. 端点URL错误
诊断步骤:
1. 检查网络连通性
bash
undefined

Test basic connectivity

测试基础连通性

ping api.example.com
ping api.example.com

Test HTTPS connectivity

测试HTTPS连通性

Test with timeout

带超时测试


**2. Check DNS Resolution**
```bash

**2. 检查DNS解析**
```bash

Check 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**
```bash
nslookup api.example.com 8.8.8.8

**3. 检查防火墙/代理**
```bash

Test if using proxy

测试是否使用代理

Check if port 443 is open

检查443端口是否开放

nc -zv api.example.com 443

**4. Test from Different Network**
```bash
nc -zv api.example.com 443

**4. 在不同网络测试**
```bash

Test 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
undefined

If primary endpoint fails, try alternative

如果主端点失败,尝试备用端点

Issue: "Invalid JSON Response"

问题: "Invalid JSON Response"

Error Message:
SyntaxError: Unexpected token < in JSON at position 0
Possible Causes:
  1. Server returned HTML error page instead of JSON
  2. Response is not valid JSON
  3. Empty response body
  4. 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
可能原因:
  1. 服务器返回HTML错误页面而非JSON
  2. 响应不是有效的JSON
  3. 响应体为空
  4. 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
undefined
try { 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"

症状:
  • API请求耗时超过5秒
  • 请求超时
  • 应用响应缓慢
诊断步骤:
1. 测量请求时间
bash
undefined

Detailed timing

使用curl测量

curl -w "@curl-format.txt" -o /dev/null -s
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/data
curl -w "@curl-format.txt" -o /dev/null -s
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/data

Use 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. 在不同位置测试**
```bash

Error Code Reference

使用在线工具在不同地区测试

CodeHTTPDescriptionSolution
AUTH_001401Invalid API keyRegenerate API key
AUTH_002401Expired API keyGenerate new key
AUTH_003403Insufficient permissionsCheck API key scopes
RATE_001429Rate limit exceededWait or upgrade plan
RATE_002429Concurrent request limitReduce parallelism
VAL_001400Missing required fieldCheck request body
VAL_002400Invalid field formatValidate input
RES_001404Resource not foundCheck resource ID
RES_002409Resource already existsUse update instead
SRV_001500Internal server errorContact support
SRV_002503Service unavailableRetry 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

  1. Check Status Page
  2. Search Documentation
  3. Check Community Forum
  4. Review this troubleshooting guide
代码HTTP状态码描述解决方案
AUTH_001401无效的API key重新生成API key
AUTH_002401过期的API key生成新的API key
AUTH_003403权限不足检查API key的权限范围
RATE_001429Rate Limit超出等待或升级套餐
RATE_002429并发请求数超出减少并行请求数
VAL_001400缺少必填字段检查请求体
VAL_002400字段格式无效验证输入内容
RES_001404资源不存在检查资源ID
RES_002409资源已存在使用更新操作替代
SRV_001500服务器内部错误联系支持团队
SRV_002503服务不可用使用退避算法重试

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!
  1. 查看状态页面
  2. 搜索文档
  3. 查看社区论坛
  4. 查阅本故障排查指南

Useful Links

联系支持团队时

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
undefined

❌ DON'T

最佳实践

✅ 建议

  • Use vague descriptions
  • Skip diagnostic steps
  • Forget to show examples
  • Assume technical knowledge
  • Skip verification steps
  • Forget edge cases
  • 从最常见的问题入手
  • 逐字记录错误信息
  • 提供分步诊断流程
  • 展示预期与实际输出对比
  • 包含代码示例
  • 记录错误码
  • 添加截图/视频
  • 链接到相关文档
  • 及时更新解决方案
  • 提供临时解决方法
  • 测试所有解决方案

Resources

❌ 避免

  • 使用模糊描述
  • 跳过诊断步骤
  • 不提供示例
  • 假设用户具备专业技术知识
  • 跳过验证步骤
  • 忽略边缘情况

参考资源