Skip to main content
Proper error handling is crucial for building robust Solana programs. Anchor provides a comprehensive error handling system with custom errors, built-in framework errors, and helpful macros for validation.

Error Types in Anchor

Anchor errors fall into two main categories:
  1. Framework Errors: Built-in errors from Anchor (error codes 100-5000)
  2. Custom Errors: Program-specific errors you define (starting at 6000)

The Error Enum

Anchor’s error type is defined as:

Defining Custom Errors

Use the #[error_code] attribute to define custom errors:

Error Code Numbers

Custom errors are automatically assigned codes starting from 6000:
Framework error code ranges:

Returning Errors

Using err! Macro

The err! macro returns an error from your instruction:

Using require! Macro

The require! macro provides a concise way to validate conditions:
If the condition is false, require! returns the specified error.

Validation Macros

Anchor provides several macros for common validation patterns:

require!

Ensures a condition is true:

require_eq!

Ensures two values are equal:

require_neq!

Ensures two values are not equal:

require_keys_eq!

Ensures two Pubkeys are equal:

require_keys_neq!

Ensures two Pubkeys are not equal:

require_gt!

Ensures the first value is greater than the second:

require_gte!

Ensures the first value is greater than or equal to the second:

Complete Example

Here’s a comprehensive example demonstrating error handling:

Error Responses

When an error occurs, Anchor provides detailed information in the transaction logs:

Client-Side Error Handling

In TypeScript clients, catch and handle errors:
Error response structure:

Common Framework Errors

Some frequently encountered Anchor framework errors:

Best Practices

  1. Use descriptive error messages: Make errors easy to understand and debug
  2. Validate early: Check conditions at the start of instructions
  3. Use specific errors: Create distinct error codes for different failure cases
  4. Leverage constraints: Use account constraints for validation when possible
  5. Check arithmetic: Use checked operations to prevent overflows
  6. Document errors: Add comments explaining when each error is used
  7. Test error cases: Write tests that verify error conditions

Using Constraints for Validation

Many validations can be done with account constraints instead of manual checks:
This approach is more concise and errors are caught during account validation.