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

# 错误处理

> EggAPI 错误响应格式和常见失败场景

EggAPI 使用统一响应信封：

```json theme={null}
{
  "data": null,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Key: 'GenerateRequest.Model' Error:Field validation for 'Model' failed on the 'oneof' tag"
  }
}
```

成功响应也使用同样信封，但 `error` 为 `null`。

## 错误码

| HTTP 状态 | Code | 常见原因 |
| - | - | - |
| `400` | `BAD_REQUEST` | 缺少路径/查询参数，或请求格式错误。 |
| `400` | `VALIDATION_ERROR` | JSON 请求体没有通过校验。 |
| `401` | `UNAUTHORIZED` | 凭证缺失、格式错误、停用、过期或无效。 |
| `403` | `FORBIDDEN` | 用户被暂停，或 session 没有权限。 |
| `403` | `INSUFFICIENT_BALANCE` | 余额不足以覆盖生成结果。 |
| `404` | `NOT_FOUND` | 任务或 dashboard 资源不存在。 |
| `429` | `RATE_LIMITED` | API Key 或 IP 超出限流。 |
| `500` | `INTERNAL_ERROR` | 后端、数据库、队列或存储失败。 |
| `502` | `UPSTREAM_ERROR` | 上游供应商网关失败。 |
| `503` | `SERVICE_UNAVAILABLE` | 服务暂不可用。 |

## 参数校验错误

生成请求当前会校验：

* `model`：`nanobanana`
* `prompt`：必填，1 到 2000 个字符
* `negative_prompt`：最多 1000 个字符
* `num_outputs`：1 到 4
* `duration`：1 到 60
* `aspect_ratio`：`16:9` 或 `9:16`
* `resolution`：`1k`、`2k` 或 `4k`
* `image_urls`：最多 9 个合法 URL
* `webhook_url`：合法 URL，最多 2048 个字符

模型名错误示例：

```json theme={null}
{
  "data": null,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Key: 'GenerateRequest.Model' Error:Field validation for 'Model' failed on the 'oneof' tag"
  }
}
```

## 鉴权错误

缺少请求头：

```json theme={null}
{
  "data": null,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Missing Authorization header"
  }
}
```

格式错误：

```json theme={null}
{
  "data": null,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid Authorization format, expected 'Bearer <token>'"
  }
}
```

## 任务失败

`GET /v1/tasks/{id}` 查询到失败任务时，HTTP 仍是 `200`，因为任务查询本身成功了。具体失败状态在 `data.status` 和 `data.error` 中表达。

```json theme={null}
{
  "data": {
    "id": "gen_abc123def456",
    "status": "failed",
    "model": "nanobanana",
    "type": "image_generate",
    "error": "generation failed: upstream provider unavailable",
    "cost": "$0.00",
    "created_at": "2026-05-08T10:30:00Z",
    "started_at": "2026-05-08T10:30:01Z",
    "completed_at": "2026-05-08T10:30:12Z"
  },
  "error": null
}
```

## 处理模式

```javascript theme={null}
async function eggapi(request) {
  const response = await fetch(request);
  const body = await response.json();

  if (body.error) {
    throw new Error(`${body.error.code}: ${body.error.message}`);
  }

  return body.data;
}
```

轮询任务时，要同时检查 HTTP 响应信封和任务状态：

```javascript theme={null}
const task = await eggapi(`https://api.eggapi.ai/v1/tasks/${taskId}`);

if (task.status === "failed") {
  throw new Error(task.error || "EggAPI task failed");
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.