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

# Enhanced Error Handling

> Comprehensive error handling with detailed context, specific error codes, and actionable suggestions for better debugging and user experience

## Overview

The WhatsApp Client SDK provides comprehensive error handling with detailed context, specific error codes, and actionable suggestions. This guide explains how to use the enhanced error system for better debugging and user experience.

<CardGroup cols={2}>
  <Card title="🔍 Detailed Error Context" icon="magnifying-glass">
    Operation details and timestamps, request/response information, phone numbers and message IDs, debugging metadata
  </Card>

  <Card title="📊 Categorized Error Codes" icon="list-check">
    Configuration errors (1000-1099), API errors (2000-2099), webhook errors (3000-3099), media errors (4000-4099), and more
  </Card>

  <Card title="💡 Actionable Suggestions" icon="lightbulb">
    Specific steps to resolve issues, context-aware recommendations, best practice guidance
  </Card>

  <Card title="🛡️ Enhanced Error Classes" icon="shield">
    Specialized error classes for different types of failures with rich debugging information
  </Card>
</CardGroup>

## Enhanced Error Classes

### EnhancedWhatsAppError (Base Class)

The base class for all enhanced errors provides detailed context and suggestions:

```typescript theme={null}
import { EnhancedWhatsAppError, WhatsAppErrorCode } from 'whatsapp-client-sdk';

// Basic usage
const error = new EnhancedWhatsAppError(
  'Message failed to send',
  WhatsAppErrorCode.API_REQUEST_FAILED,
  {
    phoneNumber: '+1234567890',
    messageId: 'msg_123',
    operation: 'send_message'
  }
);

console.log(error.toString());
// EnhancedWhatsAppError [2001]: Message failed to send
// Context: timestamp: 1640995200000, operation: send_message, phoneNumber: +1234567890, messageId: msg_123
// Suggestions:
//   • Check your access token and permissions
//   • Verify the phone number ID is correct
//   • Ensure the recipient number is valid
```

### ApiRequestError (API Failures)

Specialized for WhatsApp API request failures:

```typescript theme={null}
import { ApiRequestError, WhatsAppErrorCode } from 'whatsapp-client-sdk';

try {
  await client.sendText('+invalid', 'Hello');
} catch (error) {
  if (error instanceof ApiRequestError) {
    console.log(`Status: ${error.status}`);
    console.log(`Code: ${error.code}`);
    console.log(`Context:`, error.context);
    console.log(`Suggestions:`, error.suggestions);
    console.log(`Response:`, error.response);
  }
}
```

### WebhookProcessingError (Webhook Issues)

For webhook processing failures:

```typescript theme={null}
import { WebhookProcessingError } from 'whatsapp-client-sdk';

const webhookProcessor = client.createWebhookProcessor({
  onTextMessage: async (messages) => {
    // Your handler logic
  },
  onError: async (error) => {
    if (error instanceof WebhookProcessingError) {
      console.log('Webhook processing failed:', error.toString());
      console.log('Operation:', error.context.operation);
      console.log('Suggestions:', error.suggestions);
    }
  }
});
```

### BufferError (Message Buffering Issues)

For message buffer overflow and processing issues:

```typescript theme={null}
import { BufferError } from 'whatsapp-client-sdk';

const webhookProcessor = client.createWebhookProcessor({
  enableBuffer: true,
  bufferTimeMs: 5000,
  maxBatchSize: 10,
  onTextMessage: async (messages) => {
    // Handler logic
  },
  onError: async (error) => {
    if (error instanceof BufferError) {
      console.log('Buffer overflow detected!');
      console.log('Phone number:', error.context.phoneNumber);
      console.log('Suggestions:', error.suggestions.join(', '));
    }
  }
});
```

## Error Code Reference

### Configuration Errors (1000-1099)

<Accordion title="Configuration Error Codes">
  * `1001` - MISSING\_ACCESS\_TOKEN
  * `1002` - MISSING\_PHONE\_NUMBER\_ID
  * `1003` - MISSING\_WEBHOOK\_TOKEN
  * `1004` - INVALID\_CONFIGURATION
</Accordion>

### API Errors (2000-2099)

<Accordion title="API Error Codes">
  * `2001` - API\_REQUEST\_FAILED
  * `2002` - INVALID\_PHONE\_NUMBER
  * `2003` - MESSAGE\_TOO\_LONG
  * `2004` - UNSUPPORTED\_MESSAGE\_TYPE
  * `2005` - TEMPLATE\_NOT\_FOUND
  * `2006` - INVALID\_MEDIA\_ID
</Accordion>

### Webhook Errors (3000-3099)

<Accordion title="Webhook Error Codes">
  * `3001` - WEBHOOK\_VERIFICATION\_FAILED
  * `3002` - WEBHOOK\_PARSING\_FAILED
  * `3003` - WEBHOOK\_HANDLER\_ERROR
  * `3004` - INVALID\_WEBHOOK\_PAYLOAD
</Accordion>

### Media Errors (4000-4099)

<Accordion title="Media Error Codes">
  * `4001` - MEDIA\_UPLOAD\_FAILED
  * `4002` - MEDIA\_DOWNLOAD\_FAILED
  * `4003` - MEDIA\_TOO\_LARGE
  * `4004` - UNSUPPORTED\_MEDIA\_TYPE
</Accordion>

### Rate Limit Errors (5000-5099)

<Accordion title="Rate Limit Error Codes">
  * `5001` - RATE\_LIMIT\_EXCEEDED
  * `5002` - QUOTA\_EXCEEDED
</Accordion>

### Business Verification Errors (6000-6099)

<Accordion title="Business Verification Error Codes">
  * `6001` - BUSINESS\_NOT\_VERIFIED
  * `6002` - PHONE\_NUMBER\_NOT\_VERIFIED
</Accordion>

### Buffer/Processing Errors (7000-7099)

<Accordion title="Buffer/Processing Error Codes">
  * `7001` - BUFFER\_OVERFLOW
  * `7002` - MESSAGE\_PROCESSING\_FAILED
  * `7003` - HANDLER\_EXECUTION\_FAILED
</Accordion>

## Usage Examples

### Basic Error Handling

```typescript theme={null}
import { WhatsAppClient, ApiRequestError, WhatsAppErrorCode } from 'whatsapp-client-sdk';

const client = new WhatsAppClient({
  accessToken: process.env.WHATSAPP_ACCESS_TOKEN!,
  phoneNumberId: process.env.WHATSAPP_PHONE_NUMBER_ID!,
  webhookVerifyToken: process.env.WHATSAPP_WEBHOOK_TOKEN!,
});

async function sendMessage() {
  try {
    await client.sendText('+1234567890', 'Hello World!');
  } catch (error) {
    if (error instanceof ApiRequestError) {
      switch (error.code) {
        case WhatsAppErrorCode.INVALID_PHONE_NUMBER:
          console.log('❌ Invalid phone number format');
          console.log('💡 Suggestions:', error.suggestions.join(', '));
          break;

        case WhatsAppErrorCode.RATE_LIMIT_EXCEEDED:
          console.log('⏳ Rate limited, retrying later...');
          console.log('⚠️ Context:', error.context);
          break;

        case WhatsAppErrorCode.BUSINESS_NOT_VERIFIED:
          console.log('🏢 Business account not verified');
          console.log('📋 Steps to resolve:', error.suggestions);
          break;

        default:
          console.log('❌ API Error:', error.message);
          console.log('🔍 Debug info:', error.toJSON());
      }
    } else {
      console.log('💥 Unexpected error:', error);
    }
  }
}
```

### Advanced Webhook Error Handling

```typescript theme={null}
import {
  WhatsAppClient,
  WebhookProcessingError,
  BufferError,
  WhatsAppErrorCode
} from 'whatsapp-client-sdk';

const webhookProcessor = client.createWebhookProcessor({
  enableBuffer: true,
  bufferTimeMs: 10000,
  maxBatchSize: 50,

  onTextMessage: async (messages) => {
    if (Array.isArray(messages)) {
      console.log(`📦 Processing batch of ${messages.length} messages`);
      // Process batch
    } else {
      console.log(`📨 Processing single message: ${messages.text}`);
      // Process single message
    }
  },

  onError: async (error) => {
    console.log('\n🚨 Error occurred:');
    console.log('Type:', error.constructor.name);
    console.log('Message:', error.message);

    if (error instanceof BufferError) {
      console.log('📍 Buffer Error Details:');
      console.log('  Phone Number:', error.context.phoneNumber);
      console.log('  Operation:', error.context.operation);
      console.log('  Timestamp:', new Date(error.context.timestamp));

      console.log('\n💡 Suggestions:');
      error.suggestions.forEach(suggestion => {
        console.log(`  • ${suggestion}`);
      });

      // Handle buffer overflow
      if (error.code === WhatsAppErrorCode.BUFFER_OVERFLOW) {
        console.log('⚠️ Consider reducing buffer size or implementing backpressure');
      }

    } else if (error instanceof WebhookProcessingError) {
      console.log('📍 Webhook Processing Error Details:');
      console.log('  Operation:', error.context.operation);
      console.log('  Additional Data:', error.context.additionalData);

      if (error.originalError) {
        console.log('  Original Error:', error.originalError.message);
      }
    }
  }
});
```

## Error Monitoring and Logging

### Structured Error Logging

```typescript theme={null}
import {
  EnhancedWhatsAppError,
  ApiRequestError,
  WhatsAppErrorCode
} from 'whatsapp-client-sdk';

class ErrorLogger {
  static log(error: Error) {
    if (error instanceof EnhancedWhatsAppError) {
      // Send to monitoring service
      this.sendToMonitoring({
        service: 'whatsapp-sdk',
        error_type: error.constructor.name,
        error_code: error.code,
        message: error.message,
        context: error.context,
        suggestions: error.suggestions,
        timestamp: new Date().toISOString()
      });

      // Log to console with formatting
      console.log(`\n🚨 ${error.constructor.name} [${error.code}]`);
      console.log(`📝 ${error.message}`);
      console.log(`⏰ ${new Date(error.context.timestamp).toLocaleString()}`);

      if (error.context.phoneNumber) {
        console.log(`📞 Phone: ${error.context.phoneNumber}`);
      }

      console.log('\n💡 Suggestions:');
      error.suggestions.forEach(suggestion => {
        console.log(`  • ${suggestion}`);
      });

      // Critical errors need immediate attention
      if (this.isCritical(error.code)) {
        this.sendAlert(error);
      }
    }
  }

  static isCritical(code: WhatsAppErrorCode): boolean {
    const criticalCodes = [
      WhatsAppErrorCode.MISSING_ACCESS_TOKEN,
      WhatsAppErrorCode.BUSINESS_NOT_VERIFIED,
      WhatsAppErrorCode.QUOTA_EXCEEDED,
      WhatsAppErrorCode.BUFFER_OVERFLOW
    ];
    return criticalCodes.includes(code);
  }

  static sendToMonitoring(data: any) {
    // Implement your monitoring service integration
  }

  static sendAlert(error: EnhancedWhatsAppError) {
    console.log('🚨 CRITICAL ERROR ALERT:', error.message);
  }
}
```

## Best Practices

### 1. Always Check Error Types

```typescript theme={null}
if (error instanceof ApiRequestError) {
  // Handle API errors
} else if (error instanceof BufferError) {
  // Handle buffer errors
} else if (error instanceof WebhookProcessingError) {
  // Handle webhook errors
}
```

### 2. Use Error Codes for Logic

```typescript theme={null}
switch (error.code) {
  case WhatsAppErrorCode.RATE_LIMIT_EXCEEDED:
    await delay(5000); // Wait before retry
    break;
  case WhatsAppErrorCode.INVALID_PHONE_NUMBER:
    return { error: 'Please provide a valid phone number' };
}
```

### 3. Implement Error Recovery

```typescript theme={null}
async function sendWithRetry(phoneNumber: string, message: string, maxRetries = 3) {
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      return await client.sendText(phoneNumber, message);
    } catch (error) {
      if (error instanceof ApiRequestError) {
        if (error.code === WhatsAppErrorCode.RATE_LIMIT_EXCEEDED) {
          const delay = Math.pow(2, attempt) * 1000; // Exponential backoff
          await new Promise(resolve => setTimeout(resolve, delay));
          continue;
        }
        if (error.code === WhatsAppErrorCode.INVALID_PHONE_NUMBER) {
          throw error; // Don't retry invalid phone numbers
        }
      }

      if (attempt === maxRetries) throw error;
    }
  }
}
```

## Migration Guide

### Before (Old Error Handling)

```typescript theme={null}
try {
  await client.sendText('+1234567890', 'Hello');
} catch (error) {
  console.log('Error:', error.message); // Generic message
  // Limited debugging information
}
```

### After (Enhanced Error Handling)

```typescript theme={null}
try {
  await client.sendText('+1234567890', 'Hello');
} catch (error) {
  if (error instanceof ApiRequestError) {
    console.log('Detailed error info:', error.toString());
    console.log('Error code:', error.code);
    console.log('HTTP status:', error.status);
    console.log('Context:', error.context);
    console.log('Suggestions:', error.suggestions);
    console.log('Raw response:', error.response);
  }
}
```

## Troubleshooting Common Issues

### Buffer Overflow (Error Code: 7001)

```typescript theme={null}
// Reduce buffer size or implement backpressure
const webhookProcessor = client.createWebhookProcessor({
  enableBuffer: true,
  bufferTimeMs: 2000,     // Reduce from 10000ms
  maxBatchSize: 10,       // Reduce from 50
  // ... handlers
});
```

### Rate Limiting (Error Code: 5001)

```typescript theme={null}
// Implement exponential backoff
async function sendWithBackoff(phoneNumber: string, message: string) {
  let delay = 1000;
  const maxDelay = 30000;

  while (delay <= maxDelay) {
    try {
      return await client.sendText(phoneNumber, message);
    } catch (error) {
      if (error instanceof ApiRequestError &&
          error.code === WhatsAppErrorCode.RATE_LIMIT_EXCEEDED) {
        await new Promise(resolve => setTimeout(resolve, delay));
        delay *= 2;
        continue;
      }
      throw error;
    }
  }
}
```

### Invalid Access Token (Error Code: 1001)

```typescript theme={null}
try {
  await client.sendText('+1234567890', 'Test');
} catch (error) {
  if (error instanceof ApiRequestError &&
      error.code === WhatsAppErrorCode.MISSING_ACCESS_TOKEN) {
    console.log('Token expired. Please regenerate from Meta Business Manager.');
    // Redirect to token renewal flow
  }
}
```

<Tip>
  Enhanced error handling is available in SDK version 1.4.1 and later. All error classes are backward compatible with existing error handling patterns.

  For more error handling patterns and best practices, check out our [Best Practices Guide](/guides/best-practices).
</Tip>
