> ## Documentation Index
> Fetch the complete documentation index at: https://docs.killb.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 错误处理

> 处理 API 错误的最佳实践

## 错误响应格式

KillB 返回标准化的错误响应：

```json theme={null}
{
  "errorCode": "USER.0001",
  "message": ["User not found"],
  "statusCode": "404",
  "arguments": [
    {
      "key": "userId",
      "value": "invalid-id"
    }
  ]
}
```

## HTTP 状态码

| 状态    | 含义    | 操作     |
| ----- | ----- | ------ |
| `200` | 成功    | 处理响应   |
| `201` | 已创建   | 资源创建成功 |
| `400` | 错误请求  | 修复请求参数 |
| `401` | 未授权   | 刷新令牌   |
| `403` | 禁止    | 检查权限   |
| `404` | 未找到   | 资源不存在  |
| `409` | 冲突    | 资源已存在  |
| `429` | 请求过多  | 实现退避   |
| `500` | 服务器错误 | 使用退避重试 |

## 常见错误代码

### 身份验证错误

| 代码          | 消息    | 解决方案      |
| ----------- | ----- | --------- |
| `AUTH.0001` | 无效凭据  | 检查电子邮件/密码 |
| `AUTH.0002` | 令牌已过期 | 刷新访问令牌    |
| `AUTH.0003` | 无效令牌  | 重新身份验证    |

### 用户错误

| 代码          | 消息      | 解决方案        |
| ----------- | ------- | ----------- |
| `USER.0001` | 用户未找到   | 验证用户 ID     |
| `USER.0002` | 无效文件    | 检查文件格式      |
| `USER.0003` | 电子邮件已存在 | 使用不同的电子邮件   |
| `USER.0004` | 未成年用户   | 用户必须年满 18 岁 |

### 账户错误

| 代码             | 消息     | 解决方案    |
| -------------- | ------ | ------- |
| `ACCOUNT.0001` | 账户未找到  | 验证账户 ID |
| `ACCOUNT.0002` | 无效银行代码 | 检查支持的银行 |
| `ACCOUNT.0003` | 无效钱包地址 | 验证地址格式  |

### Ramp 错误

| 代码          | 消息     | 解决方案      |
| ----------- | ------ | --------- |
| `RAMP.0001` | 报价已过期  | 创建新报价     |
| `RAMP.0002` | 余额不足   | 检查预充值余额   |
| `RAMP.0003` | 用户限额超出 | 升级 KYC 级别 |
| `RAMP.0004` | 无效账户   | 验证账户状态    |

## 错误处理策略

```javascript theme={null}
class KillBAPIError extends Error {
  constructor(response) {
    super(response.message.join(', '));
    this.errorCode = response.errorCode;
    this.statusCode = response.statusCode;
    this.arguments = response.arguments;
  }
}

const makeAPIRequest = async (endpoint, options) => {
  try {
    const response = await fetch(endpoint, options);
    
    if (!response.ok) {
      const error = await response.json();
      throw new KillBAPIError(error);
    }
    
    return await response.json();
    
  } catch (error) {
    if (error instanceof KillBAPIError) {
      // 处理 API 错误
      console.error(`API 错误 ${error.errorCode}:`, error.message);
      
      if (error.statusCode === '401') {
        // 令牌已过期，刷新
        await refreshToken();
        return makeAPIRequest(endpoint, options);
      }
      
      if (error.errorCode === 'RAMP.0001') {
        // 报价已过期，获取新报价
        const newQuote = await getNewQuotation();
        // 使用新报价重试
      }
    }
    
    throw error;
  }
};
```

## 重试逻辑

实现指数退避：

```javascript theme={null}
const retryWithBackoff = async (fn, maxRetries = 3) => {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await fn();
    } catch (error) {
      if (i === maxRetries - 1) throw error;
      
      // 不重试客户端错误（4xx）
      if (error.statusCode && error.statusCode < 500) {
        throw error;
      }
      
      // 指数退避
      const delay = Math.pow(2, i) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
};

// 使用
const user = await retryWithBackoff(() => createUser(userData));
```

## 用户友好消息

将技术错误映射到用户消息：

```javascript theme={null}
const getUserMessage = (error) => {
  const messages = {
    'AUTH.0002': '您的会话已过期。请重新登录。',
    'USER.0003': '此电子邮件已注册。',
    'RAMP.0001': '价格报价已过期。请重试。',
    'RAMP.0003': '交易金额超出您的限额。请验证您的身份以提高限额。'
  };
  
  return messages[error.errorCode] || '发生错误。请重试。';
};
```

## 下一步

<CardGroup cols={2}>
  <Card title="速率限制" icon="gauge" href="/zh/resources/rate-limits">
    了解 API 速率限制
  </Card>

  <Card title="最佳实践" icon="star" href="/zh/resources/best-practices">
    生产集成技巧
  </Card>
</CardGroup>
