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

> ## Agent Instructions
> This page is part of the Solana developer documentation at https://solana.com/developers/docs. Append `.md` to any docs URL, or send `Accept: text/markdown`, to get the page as Markdown.
> Index of all pages: https://solana.com/llms.txt. Per-section indexes such as https://solana.com/developers/docs/payments/llms.txt are smaller; prefer them when working on one task.
> Coding agents: install the official Solana skill for current APIs and conventions with `npx skills add https://github.com/solana-foundation/solana-dev-skill` (also served at https://solana.com/SKILL.md).
> Code in the cookbook and task pages comes from tested example files. Prefer it over writing API calls from memory.

# Xử lý lỗi

> Cách kiểm thử các điều kiện lỗi và trường hợp biên

<Note>
  Yêu cầu chạy `cargo add --dev litesvm solana-sdk@4` và `cargo add --dev
  solana-system-interface --features bincode` và `cargo add --dev
  solana-transaction-error@3`
</Note>

## Bài kiểm thử hoàn chỉnh

```rust tests/error_test.rs
use litesvm::LiteSVM;
use solana_sdk::{
    signature::{Keypair, Signer},
    transaction::Transaction,
};
use solana_system_interface::instruction as system_instruction;
use solana_transaction_error::TransactionError;

#[test]
fn test_insufficient_funds_error() {
    let mut svm = LiteSVM::new();

    let alice = Keypair::new();
    let bob = Keypair::new();

    // Give Alice only 0.5 SOL
    svm.airdrop(&alice.pubkey(), 500_000_000).unwrap();

    // Try to transfer 1 SOL (should fail)
    let transfer_ix = system_instruction::transfer(
        &alice.pubkey(),
        &bob.pubkey(),
        1_000_000_000, // More than Alice has
    );

    let tx = Transaction::new_signed_with_payer(
        &[transfer_ix],
        Some(&alice.pubkey()),
        &[&alice],
        svm.latest_blockhash(),
    );

    // Verify it fails with expected error
    let result = svm.send_transaction(tx);
    assert!(result.is_err());

    let err = result.unwrap_err();
    match err.err {
        TransactionError::InstructionError(0, _) => {
            println!("Got expected error: InstructionError (insufficient funds)");
        }
        _ => panic!("Got unexpected error: {:?}", err.err),
    }

    // Verify no funds were transferred
    assert_eq!(svm.get_balance(&bob.pubkey()).unwrap_or(0), 0);
}
```

## Kiểm thử các loại lỗi khác nhau

### Tài khoản không hợp lệ

```rust
use solana_sdk::pubkey::Pubkey;

#[test]
fn test_account_not_found() {
    let mut svm = LiteSVM::new();
    let non_existent = Pubkey::new_unique();

    // This should return None
    assert!(svm.get_account(&non_existent).is_none());
}
```

### Lỗi chương trình tùy chỉnh

```rust
use solana_sdk::instruction::InstructionError;
use solana_transaction_error::TransactionError;

const YOUR_ERROR_CODE: u32 = 6000; // your program's custom error code

#[test]
fn test_custom_program_error() {
    let mut svm = LiteSVM::new();

    // Deploy program and trigger custom error
    let result = svm.send_transaction(tx);

    if let Err(e) = result {
        match e.err {
            TransactionError::InstructionError(_, InstructionError::Custom(code)) => {
                assert_eq!(code, YOUR_ERROR_CODE);
            }
            _ => panic!("Expected custom error"),
        }
    }
}
```

## Những điểm chính

1. **Xác nhận lỗi (Error Assertions)**: Dùng `assert!(result.is_err())` để xác minh lỗi xảy ra
2. **So khớp lỗi (Error Matching)**: So khớp với các loại lỗi cụ thể để đảm bảo xử lý lỗi
   chính xác
3. **Xác minh trạng thái (State Verification)**: Xác minh trạng thái không thay đổi khi xảy ra lỗi
4. **Lỗi tùy chỉnh (Custom Errors)**: Kiểm thử các mã lỗi tùy chỉnh của chương trình của bạn
5. **Trường hợp biên (Edge Cases)**: Kiểm thử các điều kiện biên và dữ liệu đầu vào không hợp lệ
