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

# Error Handling

> Complete guide to handling errors in Bigmi Bitcoin applications.

# Error Handling in Bigmi

This guide covers the most common errors you'll encounter when building Bitcoin applications with Bigmi and how to handle them effectively.

## Common Errors

| Error                                   | Common Cause                                                 | Solution                                                 |
| --------------------------------------- | ------------------------------------------------------------ | -------------------------------------------------------- |
| `ConnectorNotFoundError`                | Wallet extension not installed or available                  | Check if wallet is installed, prompt user to install     |
| `UserRejectedRequestError`              | User declined wallet connection or transaction signing       | Allow user to retry, provide clear messaging             |
| `ChainNotSupportedError`                | Wallet doesn't support the Bitcoin network (mainnet/testnet) | Switch to supported network or use different wallet      |
| `InsufficientUTXOBalanceError`          | Not enough Bitcoin balance for transaction + fees            | Check balance before transaction, suggest smaller amount |
| `TransactionNotFoundError`              | Transaction not yet broadcasted or confirmed                 | Wait for broadcast, check transaction ID                 |
| `WaitForTransactionReceiptTimeoutError` | Transaction taking longer than expected to confirm           | Increase timeout, check network congestion               |
| `AllTransportsFailedError`              | All Bitcoin RPC providers are down or unreachable            | Implement retry logic, check network connectivity        |
| `RpcRequestError`                       | Invalid RPC request or provider error                        | Validate request parameters, try different provider      |
| `TimeoutError`                          | Request took too long to complete                            | Increase timeout, implement retry mechanism              |
| `InvalidAddressError`                   | Malformed Bitcoin address format                             | Validate address format before use                       |
| `BlockNotFoundError`                    | Requested block doesn't exist                                | Check block number/hash, handle gracefully               |
| `BigmiProviderNotFoundError`            | Using Bigmi hooks outside of BigmiProvider (React)           | Wrap app with BigmiProvider                              |
| `UrlRequiredError`                      | Missing RPC URL in transport configuration                   | Provide valid RPC endpoint URL                           |

## Error Handling Patterns

### Basic Try/Catch with Bigmi

```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)
  }
}
```

### Wallet Connection Error Handling

```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>
}
```

### Transaction Retry Logic

```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
}
```

### Network Fallback Handling

```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
  }
}
```

## Troubleshooting Guide

### "Wallet extension not found"

**Symptoms**: `ConnectorNotFoundError` when trying to connect

**Solutions**:

* Check if wallet extension is installed and enabled
* Try refreshing the page
* Verify wallet supports Bitcoin network

### "Transaction failed to broadcast"

**Symptoms**: `RpcRequestError` during transaction sending

**Solutions**:

* Check if transaction hex is valid
* Verify sufficient balance for fees
* Try different RPC provider

### "Connection keeps timing out"

**Symptoms**: Frequent `TimeoutError` messages

**Solutions**:

* Increase timeout values in configuration
* Check internet connection
* Switch to different RPC providers

### "Balance shows as 0 but wallet has funds"

**Symptoms**: `getBalance` returns 0 despite having Bitcoin

**Solutions**:

* Verify address format (legacy vs SegWit)
* Check if using correct network (mainnet vs testnet)
* Wait for provider synchronization

### "React hooks not working"

**Symptoms**: `BigmiProviderNotFoundError` in React app

**Solutions**:

* Ensure `<BigmiProvider>` wraps your app
* Check provider configuration is correct
* Verify all hooks are used within provider context

### Replace-By-Fee (RBF) handling

**Symptoms**: Transaction gets replaced unexpectedly

**Solutions**:

* Monitor `waitForTransaction` for replacement events
* Handle `onReplaced` callback appropriately
* Update UI when transaction is replaced

## Best Practices

1. **Always wrap Bitcoin operations in try/catch blocks**
2. **Use specific error types for targeted error handling**
3. **Implement retry logic for network operations**
4. **Provide clear user feedback for wallet errors**
5. **Configure multiple RPC providers for reliability**
6. **Validate addresses before using them**
7. **Check balances before attempting transactions**
8. **Handle RBF scenarios in transaction monitoring**

## Error Recovery Strategies

* **Automatic Retry**: For network timeouts and temporary failures
* **User Retry**: For wallet rejections and user errors
* **Fallback Providers**: For RPC provider failures
* **Graceful Degradation**: Show cached data when providers are down
* **Clear Messaging**: Help users understand and resolve issues
