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

# 错误处理

> 使用 TheoApiError 处理 API 错误。

## TheoApiError

所有 REST API 错误都会以带有结构化详情的 `TheoApiError` 实例抛出。

```typescript theme={null}
import { Theo, TheoApiError } from "@hitheo/sdk";

try {
  const res = await theo.complete({ prompt: "Hello" });
} catch (err) {
  if (err instanceof TheoApiError) {
    console.log(err.status);              // 401
    console.log(err.message);             // "Theo API error 401: Invalid API key"
    console.log(err.details?.code);       // "invalid_api_key"
    console.log(err.details?.type);       // "authentication_error"
    console.log(err.details?.request_id); // "req_9f2e1a" — share in support tickets
    console.log(err.url);                 // "https://www.hitheo.ai/api/v1/completions"
  }
}
```

## 错误属性

| 属性 | 类型 | 说明 |
| - | - | - |
| `status` | `number` | HTTP 状态码（网络/超时/取消时为 `0`） |
| `kind` | `string` | `"http"` \| `"timeout"` \| `"cancelled"` \| `"network"` —— 应基于此字段分支处理，而不是做字符串匹配 |
| `message` | `string` | 可读的错误信息 |
| `body` | `string` | 原始响应体 |
| `url` | `string` | 请求 URL |
| `details` | `object \| null` | 解析后的 `{ message, type, code, request_id }` |

## 错误类型

`TheoApiError` 是基类 —— 下面每种错误都是 `TheoApiError` 的实例，因此现有的 catch 代码块仍然可以正常工作。若需要精确处理，请基于子类（或 `err.kind`）分支：

* **`TheoTimeoutError`**（`kind: "timeout"`）—— SDK 在 `timeoutMs`（单次请求 / 流连接）或 `streamIdleTimeoutMs`（流空闲）超时后主动中止。相关超时预算保存在 `.timeoutMs` 中。**不会**在 POST 请求上自动重试。
* **`TheoCancelledError`**（`kind: "cancelled"`）—— 你通过 `TheoStream.cancel()` 或传给 `waitForJob()` 的 `AbortSignal` 主动中止了请求。
* **`TheoUsageError`**（继承自 `Error`，而非 `TheoApiError`）—— 在发起任何网络调用之前，因误用而同步抛出，例如向 `complete()` / `stream()` 传入 `mode: "research" | "video"`（应改用[异步任务](/guides/async-jobs)方法）。

```typescript theme={null}
import { TheoApiError, TheoTimeoutError, TheoCancelledError, TheoUsageError } from "@hitheo/sdk";

try {
  await theo.complete({ prompt });
} catch (err) {
  if (err instanceof TheoUsageError) { /* fix the call shape */ }
  else if (err instanceof TheoTimeoutError) { console.error(`timed out after ${err.timeoutMs}ms`); }
  else if (err instanceof TheoCancelledError) { /* user aborted — not an error */ }
  else if (err instanceof TheoApiError && err.kind === "network") { /* offline / retry later */ }
}
```

## 流式错误

SSE 的 `error` 事件携带的**信封结构与 REST 错误响应体相同**——两者可以复用同一套处理逻辑。

```typescript theme={null}
const stream = theo.stream({ prompt: "..." });

for await (const event of stream) {
  if (event.type === "error") {
    const { message, type, code, request_id } = event.data.error;
    throw new Error(`[${type}/${code}] ${message} (request_id=${request_id})`);
  }
  // ...
}
```

这一点与 `0.1.x` 版本不同，当时流式错误只有 `{ message }`。完整的信封结构请参见[流式补全](/api-reference/completions/streaming)参考文档。

## 首次运行诊断

`theo.verify()` 不会直接抛出原始错误，而是返回带有修复建议的结构化诊断结果：

```typescript theme={null}
const result = await theo.verify();
if (!result.authenticated) {
  console.error(result.error);  // underlying error
  console.error(result.hint);   // e.g. "Authentication failed. Confirm your API key..."
}
```

遇到 401 错误时，应将此调用作为排查的第一步。常见故障场景请参见[401 故障排查](/troubleshooting/401-errors)。

## 自动重试

SDK 会在以下情况下自动重试：

* **429** —— 触发限流（遵循 `Retry-After` 响应头，最多等待 60 秒）
* **5xx** —— 服务器错误（指数退避：1 秒、2 秒、4 秒，最长 8 秒）
  客户端错误（400、401、403、404）**不会**被重试。**非幂等的 POST 请求**（`complete`、`research`、`video`）**的超时不会被重试**——重新发起请求可能导致请求被重复执行并重复计费；如果确实需要重试，请自行实现重试逻辑并配合 `Idempotency-Key` 使用。完整的重试模型（包括流式**空闲**超时）请参见[超时与重试](/sdk-reference/timeouts-and-retries)。
  配置方式：

```typescript theme={null}
const theo = new Theo({
  apiKey: "...",
  maxRetries: 3,               // Default: 2
  timeoutMs: 60000,            // Default: 30000 (unary total; stream connect)
  streamIdleTimeoutMs: 180000, // Default: 120000 (between-chunks)
});
```

## 取消请求

`TheoStream.cancel()` 会中止正在进行的流式请求，且不会抛出异常。底层的 `fetch` 会通过 `AbortController` 被中止；后续事件将不再到达，迭代器会正常结束。

```typescript theme={null}
const stream = theo.stream({ prompt: "..." });
setTimeout(() => stream.cancel(), 3000); // Graceful "Stop generating"
for await (const event of stream) { /* ... */ }
```


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