> ## 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.

# 错误处理

> 在 Bigmi Bitcoin 应用中处理错误的完整指南。

# Bigmi 中的错误处理

本指南介绍使用 Bigmi 构建 Bitcoin 应用时最常遇到的错误，以及如何有效地处理它们。

## 常见错误

| 错误                                      | 常见原因                                    | 解决方案                 |
| --------------------------------------- | --------------------------------------- | -------------------- |
| `ConnectorNotFoundError`                | 钱包扩展未安装或不可用                             | 检查钱包是否已安装，提示用户安装     |
| `UserRejectedRequestError`              | 用户拒绝了钱包连接或交易签名                          | 允许用户重试，提供清晰的提示信息     |
| `ChainNotSupportedError`                | 钱包不支持该 Bitcoin 网络（主网/测试网）               | 切换到受支持的网络或使用其他钱包     |
| `InsufficientUTXOBalanceError`          | Bitcoin 余额不足以支付交易 + 费用                  | 在交易前检查余额，建议使用较小的金额   |
| `TransactionNotFoundError`              | 交易尚未广播或确认                               | 等待广播，检查交易 ID         |
| `WaitForTransactionReceiptTimeoutError` | 交易确认耗时超出预期                              | 增大超时时间，检查网络拥堵情况      |
| `AllTransportsFailedError`              | 所有 Bitcoin RPC 提供商都宕机或无法访问              | 实现重试逻辑，检查网络连接        |
| `RpcRequestError`                       | 无效的 RPC 请求或提供商错误                        | 校验请求参数，尝试其他提供商       |
| `TimeoutError`                          | 请求耗时过长而未能完成                             | 增大超时时间，实现重试机制        |
| `InvalidAddressError`                   | Bitcoin 地址格式错误                          | 在使用前校验地址格式           |
| `BlockNotFoundError`                    | 请求的区块不存在                                | 检查区块编号/哈希，优雅地处理      |
| `BigmiProviderNotFoundError`            | 在 BigmiProvider 之外使用 Bigmi hooks（React） | 用 BigmiProvider 包裹应用 |
| `UrlRequiredError`                      | 传输配置中缺少 RPC URL                         | 提供有效的 RPC 端点 URL     |

## 错误处理模式

### 使用 Bigmi 的基本 Try/Catch

```typescript theme={"system"}
import { getUTXOs, InsufficientUTXOBalanceError } from '@bigmi/core'

try {
  const utxos = await getUTXOs(client, { address: 'bc1...', minValue: 34954 })
  const utxoBalance = utxos.reduce((total, utxo) => total + utxo.value, 0)
  console.log(`UTXO balance: ${utxoBalance} sats`)
} catch (error) {
  if (error instanceof InsufficientUTXOBalanceError) {
    console.error('Insufficient balance for transaction')
  } else {
    console.error('Unknown error:', error.message)
  }
}
```

### 钱包连接错误处理

```typescript theme={"system"}
import { useConnect } from '@bigmi/react'
import { 
  ConnectorNotFoundError, 
  UserRejectedRequestError 
} from '@bigmi/client'

function ConnectWallet() {
  const { connect } = useConnect()

  const handleConnect = async () => {
    try {
      await connect({ connector: xverse() })
    } catch (error) {
      if (error instanceof ConnectorNotFoundError) {
        alert('Please install Xverse wallet extension')
      } else if (error instanceof UserRejectedRequestError) {
        alert('Connection rejected. Please try again.')
      } else {
        console.error('Connection failed:', error)
      }
    }
  }

  return <button onClick={handleConnect}>Connect Wallet</button>
}
```

### 交易重试逻辑

```typescript theme={"system"}
import { 
  sendUTXOTransaction, 
  waitForTransaction,
  withRetry,
  TimeoutError,
  TransactionNotFoundError, 
  getBalance
} from '@bigmi/core'

// Using Bigmi's built-in withRetry utility

// Simple retry with fixed delay
async function getBalanceWithRetry(client, address) {
  return withRetry(
    () => getBalance(client, { address }),
    {
      delay: 2000,     // 2 seconds between retries
      retryCount: 3,   // Try 3 times total
    }
  )
}

async function sendTransactionWithRetry(client, txHex) {
  // Retry transaction broadcasting with exponential backoff
  const txId = await withRetry(
    () => sendUTXOTransaction(client, { hex: txHex }),
    {
      delay: ({ count }) => Math.pow(2, count) * 1000, // 1s, 2s, 4s...
      retryCount: 3,
      shouldRetry: ({ error }) => 
        error instanceof TimeoutError || 
        error instanceof TransactionNotFoundError
    }
  )
  
  // Wait for confirmation with retry logic
  const receipt = await withRetry(
    () => waitForTransaction(client, {
      txId,
      txHex,
      timeout: 30_000 // 30 seconds per attempt
    }),
    {
      delay: 5000, // 5 second delay between retries
      retryCount: 5,
      shouldRetry: ({ error }) => error instanceof TimeoutError
    }
  )
  
  return receipt
}
```

### 网络回退处理

```typescript theme={"system"}
import { 
  createClient, 
  fallback, 
  mempool, 
  blockchair,
  AllTransportsFailedError 
} from '@bigmi/core'

// Create client with multiple providers for reliability
const client = createClient({
  chain: bitcoin,
  transport: fallback([
    mempool(),
    blockchair(),
    // Add more providers as fallbacks
  ])
})

try {
  const balance = await getBalance(client, { address })
} catch (error) {
  if (error instanceof AllTransportsFailedError) {
    console.error('All Bitcoin providers are down. Please try again later.')
    // Show user-friendly error message
  }
}
```

## 故障排查指南

### “Wallet extension not found”（未找到钱包扩展）

**症状**：尝试连接时出现 `ConnectorNotFoundError`

**解决方案**：

* 检查钱包扩展是否已安装并启用
* 尝试刷新页面
* 确认钱包支持 Bitcoin 网络

### “Transaction failed to broadcast”（交易广播失败）

**症状**：发送交易期间出现 `RpcRequestError`

**解决方案**：

* 检查交易 hex 是否有效
* 确认有足够余额支付费用
* 尝试其他 RPC 提供商

### “Connection keeps timing out”（连接持续超时）

**症状**：频繁出现 `TimeoutError` 消息

**解决方案**：

* 增大配置中的超时值
* 检查网络连接
* 切换到其他 RPC 提供商

### “Balance shows as 0 but wallet has funds”（余额显示为 0 但钱包有资金）

**症状**：尽管持有 Bitcoin，`getBalance` 仍返回 0

**解决方案**：

* 校验地址格式（legacy 与 SegWit）
* 检查是否使用了正确的网络（主网与测试网）
* 等待提供商同步

### “React hooks not working”（React hooks 无法工作）

**症状**：React 应用中出现 `BigmiProviderNotFoundError`

**解决方案**：

* 确保 `<BigmiProvider>` 包裹了你的应用
* 检查提供商配置是否正确
* 确认所有 hooks 都在提供商上下文中使用

### Replace-By-Fee（RBF）处理

**症状**：交易意外被替换

**解决方案**：

* 通过 `waitForTransaction` 监控替换事件
* 妥善处理 `onReplaced` 回调
* 交易被替换时更新 UI

## 最佳实践

1. **始终将 Bitcoin 操作包裹在 try/catch 块中**
2. **使用特定的错误类型进行针对性的错误处理**
3. **为网络操作实现重试逻辑**
4. **为钱包错误提供清晰的用户反馈**
5. **配置多个 RPC 提供商以提高可靠性**
6. **在使用地址前对其进行校验**
7. **在尝试交易前检查余额**
8. **在交易监控中处理 RBF 场景**

## 错误恢复策略

* **自动重试**：用于网络超时和临时故障
* **用户重试**：用于钱包拒绝和用户错误
* **回退提供商**：用于 RPC 提供商故障
* **优雅降级**：在提供商宕机时展示缓存数据
* **清晰的提示**：帮助用户理解并解决问题
