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

# 错误处理

> 使用 LI.FI Composer 时如何处理错误和故障模式，包括 API 错误、交易失败和跨链边缘情况。

本页介绍你在使用 Composer 时可能遇到的错误以及如何处理它们。Composer 使用与更广泛的 LI.FI API 相同的错误系统，此处记录的错误针对 Composer 特有的场景进行了情境化说明。

***

## API 错误（报价/路由请求）

当通过 `GET /quote` 或 `POST /advanced/routes` 请求 Composer 报价时，API 可能返回错误。这些错误遵循标准的 LI.FI 错误格式：

1. **HTTP 状态码**（例如 200、404、429、500）
2. **LI.FI 错误码**（数字）
3. **错误信息**（人类可读）

### 相关的 API 错误码

| 错误码    | 名称                              | Composer 情境                                                               |
| ------ | ------------------------------- | ------------------------------------------------------------------------- |
| `1001` | `FailedToBuildTransactionError` | Composer 无法构建该交易。vault 代币可能无效，或协议可能暂时不可用。                                 |
| `1002` | `NoQuoteError`                  | 未找到 Composer 路由。vault 代币地址可能不受支持，或所请求路径的流动性不足。                            |
| `1004` | `NotProcessableError`           | 该请求无法处理。请检查所有参数是否有效。                                                      |
| `1005` | `RateLimitError`                | 请求过多。请实现退避和重试。参见[速率限制](/api-reference/rate-limits)。                       |
| `1007` | `SlippageError`                 | 价格影响超出滑点容忍度。请增大 `slippage` 参数或减少金额。                                       |
| `1009` | `TimeoutError`                  | 请求超时。请重试该请求。                                                              |
| `1011` | `ValidationError`               | 参数无效。请检查 `fromChain`、`toChain`、`fromToken`、`toToken` 和 `fromAmount` 是否有效。 |

有关完整的 API 错误码列表，请参阅[错误码](/api-reference/error-codes)。

***

## 工具错误

API 也可能返回描述底层协议问题的工具特有错误。这些错误使用 `ToolError` 格式：

```typescript theme={"system"}
interface ToolError {
  errorType: "NO_QUOTE";
  code: string;
  action: Action;
  tool: string;
  message: string;
}
```

### 相关的工具错误码

| 错误码                       | 说明         | Composer 情境                                     |
| ------------------------- | ---------- | ----------------------------------------------- |
| `NO_POSSIBLE_ROUTE`       | 未找到该操作的路由  | vault 代币可能不受支持，或该源链/目标链组合不可用                    |
| `INSUFFICIENT_LIQUIDITY`  | 工具的流动性不足   | 没有足够的流动性来完成 Composer flow 中的交换部分                |
| `TOOL_TIMEOUT`            | 第三方工具超时    | 底层协议或 DEX 超时。请重试该请求。                            |
| `AMOUNT_TOO_LOW`          | 转账金额过低     | 请增大 `fromAmount`。由于涉及多个步骤，Composer 路由的最低金额可能更高。 |
| `AMOUNT_TOO_HIGH`         | 金额超出可用流动性  | 请减小 `fromAmount` 或拆分为多笔交易。                      |
| `FEES_HIGHER_THAN_AMOUNT` | 费用超过转账金额   | 请增大 `fromAmount`，使其能够覆盖 gas 和协议费用。              |
| `TOOL_SPECIFIC_ERROR`     | 第三方工具返回了错误 | 目标协议返回了错误。请检查该 vault 是否正在接受存入。                  |

### 示例：处理工具错误

```ts theme={"system"}
try {
  const quote = await axios.get("https://li.quest/v1/quote", { params });
} catch (error) {
  if (error.response?.data?.errors) {
    for (const toolError of error.response.data.errors) {
      console.error(`Tool: ${toolError.tool}`);
      console.error(`Code: ${toolError.code}`);
      console.error(`Message: ${toolError.message}`);

      switch (toolError.code) {
        case "NO_POSSIBLE_ROUTE":
          // Vault token may not be supported
          console.log(
            "Check that the toToken is a supported vault token address.",
          );
          break;
        case "INSUFFICIENT_LIQUIDITY":
          // Try a smaller amount
          console.log("Try reducing the fromAmount.");
          break;
        case "AMOUNT_TOO_LOW":
          // Increase the amount
          console.log("Increase the fromAmount.");
          break;
        case "TOOL_TIMEOUT":
          // Retry
          console.log("Retrying...");
          break;
      }
    }
  }
}
```

***

## 交易失败

### 执行前模拟失败

Composer 在返回报价之前会模拟整个执行路径。如果模拟失败，API 会返回一个错误，**而非**一笔会在链上回滚的交易。这可以避免用户在失败的交易上浪费 gas。

常见的模拟失败原因：

* vault 未接受存入（已暂停、已满或受限）
* 代币路径涉及不兼容的代币
* 交换路径中流动性不足

### 链上交易回滚

在极少数情况下，即便通过了模拟，交易也可能在链上回滚（例如由于内存池抢跑，或模拟与执行之间状态发生快速变化）。如果发生这种情况：

1. 用户的代币仍保留在其钱包中（对于同链原子交易）
2. 被回滚交易的 gas 费用仍会被消耗
3. 使用一个新的报价重试，以获得更新后的模拟结果

***

## 跨链故障模式

跨链 Composer flow 分为两个阶段。每个阶段在其所在链内是原子的，但整体 flow 是最终一致的。

### 状态值

轮询 `GET /v1/status` 以跟踪跨链 Composer 交易。状态值为：

| Status      | 说明           |
| ----------- | ------------ |
| `NOT_FOUND` | 交易不存在或尚未被打包  |
| `INVALID`   | 哈希未与所请求的工具关联 |
| `PENDING`   | 转账仍在进行中      |
| `DONE`      | 交易成功完成       |
| `FAILED`    | 转账失败         |

### 子状态值

#### 当 Status 为 `PENDING` 时

| Substatus                      | 说明             |
| ------------------------------ | -------------- |
| `WAIT_SOURCE_CONFIRMATIONS`    | 正在等待源链确认       |
| `WAIT_DESTINATION_TRANSACTION` | 正在等待目标链交易      |
| `BRIDGE_NOT_AVAILABLE`         | 桥 API 不可用      |
| `CHAIN_NOT_AVAILABLE`          | 源链/目标链 RPC 不可用 |
| `REFUND_IN_PROGRESS`           | 退款进行中（如果支持）    |
| `UNKNOWN_ERROR`                | 状态不确定          |

#### 当 Status 为 `DONE` 时

| Substatus   | 说明       |
| ----------- | -------- |
| `COMPLETED` | 转账成功     |
| `PARTIAL`   | 仅完成了部分转账 |
| `REFUNDED`  | 代币已退回    |

#### 当 Status 为 `FAILED` 时

| Substatus                       | 说明        |
| ------------------------------- | --------- |
| `NOT_PROCESSABLE_REFUND_NEEDED` | 无法完成，需要退款 |
| `OUT_OF_GAS`                    | 交易 gas 耗尽 |
| `SLIPPAGE_EXCEEDED`             | 收到的金额过低   |
| `INSUFFICIENT_ALLOWANCE`        | 代币授权额度不足  |
| `INSUFFICIENT_BALANCE`          | 代币余额不足    |
| `EXPIRED`                       | 交易已过期     |
| `UNKNOWN_ERROR`                 | 未知或无效状态   |
| `REFUNDED`                      | 代币已退回     |

### 处理跨链失败

```ts theme={"system"}
const status = await axios
  .get("https://li.quest/v1/status", {
    params: { txHash, fromChain, toChain },
  })
  .then((r) => r.data);

switch (status.status) {
  case "DONE":
    if (status.substatus === "COMPLETED") {
      console.log("Composer deposit completed successfully.");
    } else if (status.substatus === "PARTIAL") {
      console.log(
        "Partial completion: bridged tokens may be on destination chain but not deposited.",
      );
    } else if (status.substatus === "REFUNDED") {
      console.log("Tokens were refunded to source chain.");
    }
    break;

  case "FAILED":
    if (status.substatus === "SLIPPAGE_EXCEEDED") {
      console.log("Slippage exceeded. Retry with higher slippage tolerance.");
    } else if (status.substatus === "INSUFFICIENT_ALLOWANCE") {
      console.log("Insufficient allowance. Approve tokens before retrying.");
    } else if (status.substatus === "NOT_PROCESSABLE_REFUND_NEEDED") {
      console.log("Transfer cannot complete. Refund will be processed.");
    } else {
      console.error(
        "Transfer failed:",
        status.substatus,
        status.substatusMessage,
      );
    }
    break;

  case "PENDING":
    console.log("Still in progress:", status.substatus);
    break;
}
```

有关完整的状态参考，请参阅[交易状态跟踪](/introduction/user-flows-and-examples/status-tracking)。

***

## 常见的 Composer 问题

| 问题           | 原因                          | 解决方法                                             |
| ------------ | --------------------------- | ------------------------------------------------ |
| 未返回路由        | `toToken` 不是受支持的 vault 代币地址 | 对照[支持的协议](/composer/protocols-and-chains)列表核实该地址 |
| 模拟失败         | vault 已暂停、已满或未接受存入          | 直接检查该协议的状态                                       |
| 交易回滚         | 模拟与执行之间状态发生变化               | 使用一个新的报价重试                                       |
| 跨链卡在 PENDING | 桥速度慢或拥堵                     | 请等待并继续轮询。如果仍然卡住，请查看桥自己的状态页面。                     |
| 部分完成         | 桥接成功但目标链操作失败                | 用户在目标链上持有代币。他们可以直接重试存入。                          |

***

## 相关页面

<CardGroup cols={2}>
  <Card title="Error Codes" icon="circle-exclamation" href="/api-reference/error-codes">
    完整的 LI.FI API 错误码参考
  </Card>

  <Card title="Status Tracking" icon="signal" href="/introduction/user-flows-and-examples/status-tracking">
    完整的 status 和 substatus 参考
  </Card>

  <Card title="API Parameters" icon="sliders" href="/composer/lifi-api/reference/api-parameters">
    Composer 特有的 API 参数
  </Card>

  <Card title="Limitations" icon="circle-info" href="/composer/lifi-api/reference/limitations">
    当前的 Composer 限制
  </Card>
</CardGroup>
