Error Handling

Error Handling

Always wrap provider and contract calls in try-catch-finally blocks to ensure robust error handling. This pattern guarantees that exceptions are caught and handled appropriately, preventing unhandled errors from crashing the application. The finally block ensures that cleanup operations, such as releasing resources or resetting state, are executed regardless of whether the operation succeeds or fails, maintaining application stability and preventing resource leaks.

Checking OP_NET Specific Error Types

typescript
Using try-catch-finally
import { OPNetError } from 'opnet';

try {
    // Function call here
    await ....
} catch (error) {
    if (error instanceof OPNetError) {
        // OPNET specific error
        console.error('OPNet Error');
        console.error('  Message:', error.message);
        console.error('  Code:', error.code);
    } else if (error instanceof Error) {
        // Network or other error
        if (error.message.includes('not found')) {
           console.log('Contract not deployed at address');
        } else if (error.message.includes('Insufficient')) {
            console.error('Not enough funds');
        } else if (error.message.includes('timeout')) {
            console.error('Request timed out');
        } else {
            console.error('Unknown error:', error.message);
        }

        return null;
    } finally{
        // Do cleanup here like closing/disconnecting a provider
    }
}

Common Error Scenarios

Error Type Cause Solution
Timeout Request took too long. Increase timeout or retry.
Connection Refused Server unavailable. Check URL, retry later.
Invalid Response Malformed RPC response. Check request parameters.
Block Not Found Non-existent block. Verify block number exists.
Revert Contract execution failed. Check simulation first.
Contract Not Found Contract not deployed at address. Verify address.

Safe Wrapper Methods

Creating safe wrapper methods around operations enables comprehensive error handling and provides a consistent approach to managing exceptions. These wrappers intercept errors, allowing specific error types to be handled gracefully such as returning null for missing resources while re-throwing unexpected errors for further handling. This pattern improves code maintainability and ensures predictable behavior across the application.

typescript
Creating a safe wrapper
// Comprehensive error handling
async function safeGetBlock(height: bigint) : Promise<Block | null> {
    try {
        return await provider.getBlock(height);
    } catch (error) {
        if (error instanceof Error) {
            if (error.message.includes('not found')) {
                console.warn('Block not found');
                return null;
            }
        }
        throw error;  // Re-throw unknown errors
    }
}