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

# 错误处理

> 了解如何处理 API 调用中的错误

# 错误处理

了解如何处理 AI发型设计 API 调用中可能出现的错误。

## 错误响应格式

所有 API 错误都遵循统一的响应格式：

```json theme={null}
{
  "request_id": "请求ID",
  "log_id": "日志ID",
  "error_code": 错误代码,
  "error_msg": "错误消息",
  "error_detail": {
    "status_code": HTTP状态码,
    "code": "错误代码",
    "code_message": "错误代码描述",
    "message": "详细错误信息"
  }
}
```

## 常见错误类型

### 认证错误 (401)

```json theme={null}
{
  "error_code": 401,
  "error_msg": "Unauthorized",
  "error_detail": {
    "status_code": 401,
    "code": "UNAUTHORIZED",
    "code_message": "Invalid or missing API key",
    "message": "Please provide a valid API key"
  }
}
```

**解决方案**：

* 检查 API Key 是否正确
* 确保 API Key 在请求头中正确设置
* 验证 API Key 是否有效

### 参数错误 (400)

```json theme={null}
{
  "error_code": 400,
  "error_msg": "Bad Request",
  "error_detail": {
    "status_code": 400,
    "code": "MISSING_PARAMETERS",
    "code_message": "Missing required parameters",
    "message": "Missing parameters. - [task_type]"
  }
}
```

**解决方案**：

* 检查是否缺少必需参数
* 验证参数格式是否正确
* 确保参数值在有效范围内

### 文件错误 (422)

```json theme={null}
{
  "error_code": 422,
  "error_msg": "Unprocessable Entity",
  "error_detail": {
    "status_code": 422,
    "code": "ERROR_NO_FACE_IN_FILE",
    "code_message": "No face detected in the file",
    "message": "pic not has face"
  }
}
```

**解决方案**：

* 确保图片中包含清晰的人脸
* 检查图片是否符合要求
* 使用人脸分析 API 预先验证

## 错误处理最佳实践

### 1. 检查 HTTP 状态码

```javascript theme={null}
const response = await fetch(url, options);
if (!response.ok) {
  const error = await response.json();
  console.error('API Error:', error);
  // 处理错误
}
```

### 2. 解析错误详情

```javascript theme={null}
function handleApiError(error) {
  const { error_code, error_msg, error_detail } = error;
  
  switch (error_code) {
    case 401:
      console.error('认证失败:', error_msg);
      // 重新获取 API Key
      break;
    case 400:
      console.error('参数错误:', error_detail.message);
      // 检查参数
      break;
    case 422:
      console.error('文件错误:', error_detail.message);
      // 检查文件
      break;
    default:
      console.error('未知错误:', error_msg);
  }
}
```

### 3. 重试机制

```javascript theme={null}
async function callApiWithRetry(url, options, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(url, options);
      if (response.ok) {
        return await response.json();
      }
      
      const error = await response.json();
      if (error.error_code === 401) {
        // 认证错误，不重试
        throw error;
      }
      
      // 其他错误，等待后重试
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
    } catch (error) {
      if (i === maxRetries - 1) {
        throw error;
      }
    }
  }
}
```

## 异步任务错误处理

对于异步任务，还需要处理任务状态：

```javascript theme={null}
async function pollAsyncTask(taskId, maxAttempts = 100) {
  for (let i = 0; i < maxAttempts; i++) {
    const result = await queryAsyncTask(taskId);
    
    if (result.task_status === 2) {
      // 任务成功完成
      return result;
    } else if (result.task_status === -1) {
      // 任务失败
      throw new Error('Task failed');
    }
    
    // 等待 5 秒后重试
    await new Promise(resolve => setTimeout(resolve, 5000));
  }
  
  throw new Error('Task timeout');
}
```

## 调试技巧

### 1. 记录请求信息

```javascript theme={null}
console.log('Request URL:', url);
console.log('Request Headers:', headers);
console.log('Request Body:', body);
```

### 2. 记录响应信息

```javascript theme={null}
console.log('Response Status:', response.status);
console.log('Response Headers:', response.headers);
console.log('Response Body:', await response.text());
```

### 3. 使用 request\_id 和 log\_id

```javascript theme={null}
if (error.request_id) {
  console.log('Request ID:', error.request_id);
}
if (error.log_id) {
  console.log('Log ID:', error.log_id);
}
```

## 相关链接

* [响应说明](/essentials/response-description)
* [图片要求](/essentials/image-requirements)
* [错误代码](/essentials/errors)
