# Error Handling Documentation

This document provides detailed information about the error handling mechanisms in the Sofya Transcription SDK.

## Overview

The Sofya Transcription SDK provides comprehensive error handling to ensure a robust and reliable transcription experience. The SDK uses a combination of error throwing, event emission, and logging to handle errors at different stages of the transcription process.

## Error Handling Strategies

### 1. Validation Errors

The SDK validates inputs and configurations before attempting to connect to a provider or start transcription. If validation fails, the SDK will throw an error with a descriptive message.

Examples of validation errors:

- Missing API key
- Missing endpoint for provider connection
- Missing configuration for provider connection
- Invalid connection object

### 2. Connection Errors

The SDK handles connection errors by attempting to connect to alternative providers or endpoints if available. If all connection attempts fail, the SDK will throw an error.

Examples of connection errors:

- Authentication failure
- Network connectivity issues
- Provider service unavailability
- Invalid provider configuration

### 3. Transcription Errors

The SDK handles transcription errors by emitting an 'error' event with the error details. This allows the application to handle the error appropriately.

Examples of transcription errors:

- Microphone access denied
- Audio processing errors
- Provider service errors during transcription

## Error Events

The SDK emits the following error-related events:

- `error`: Emitted when an error occurs during any stage of the transcription process.

Example:

```typescript
transcriber.on('error', (error) => {
  console.error('Transcription error:', error);
  // Handle the error appropriately
});
```

## Error Logging

The SDK logs errors to the console to help with debugging. The log level and format depend on the severity of the error:

- `console.error`: Used for critical errors that prevent the SDK from functioning.
- `console.warn`: Used for non-critical errors that don't prevent the SDK from functioning but may affect its performance or reliability.

## Error Recovery

The SDK provides mechanisms for error recovery:

1. **Automatic Provider Fallback**: When using the API key connection mode, the SDK will automatically attempt to connect to alternative providers if the initial connection fails.

2. **Event-Based Error Handling**: The SDK emits error events that allow the application to handle errors appropriately, such as retrying the connection or displaying an error message to the user.

## Best Practices for Error Handling

### 1. Always Listen for Error Events

```typescript
transcriber.on('error', (error) => {
  console.error('Transcription error:', error);
  // Handle the error appropriately
});
```

### 2. Use Try-Catch Blocks for Initialization

```typescript
try {
  const transcriber = new SofyaTranscriber({
    apiKey: 'YOUR_API_KEY',
    config: {
      language: 'en-US'
    }
  });
  
  // Use the transcriber
} catch (error) {
  console.error('Failed to initialize transcriber:', error);
  // Handle the error appropriately
}
```

### 3. Check for Ready Event Before Starting Transcription

```typescript
transcriber.on('ready', () => {
  console.log('Transcription service is ready');
  
  // Get media stream and start transcription
  navigator.mediaDevices.getUserMedia({ audio: true })
    .then(mediaStream => {
      transcriber.startTranscription(mediaStream);
    })
    .catch(error => {
      console.error('Error accessing microphone:', error);
      // Handle the error appropriately
    });
});
```

### 4. Implement Retry Logic for Critical Operations

```typescript
function startTranscriptionWithRetry(transcriber, mediaStream, maxRetries = 3) {
  let retryCount = 0;
  
  function attemptStart() {
    try {
      transcriber.startTranscription(mediaStream);
    } catch (error) {
      console.error(`Failed to start transcription (attempt ${retryCount + 1}/${maxRetries}):`, error);
      
      if (retryCount < maxRetries) {
        retryCount++;
        setTimeout(attemptStart, 1000); // Retry after 1 second
      } else {
        console.error('Failed to start transcription after multiple attempts');
        // Handle the error appropriately
      }
    }
  }
  
  attemptStart();
}
```

## Common Error Scenarios and Solutions

### 1. API Key Authentication Failure

**Error Message**: "Could not authenticate. Please validate your API key and try again."

**Solution**: Verify that the API key is correct and has not expired. If the issue persists, contact Sofya support.

### 2. Provider Connection Failure

**Error Message**: "Failed to connect to any provider. Please check your API key and try again."

**Solution**: Check your network connectivity and verify that the provider services are available. If the issue persists, try using a different provider or contact Sofya support.

### 3. Microphone Access Denied

**Error Message**: "Error accessing microphone: NotAllowedError"

**Solution**: Ensure that the user has granted permission to access the microphone. If the permission was denied, the user will need to grant permission through their browser settings.

### 4. Transcription Service Error

**Error Message**: "Transcription service error: [provider-specific error]"

**Solution**: Check the provider-specific error message for details. Common issues include invalid configuration, network connectivity problems, or provider service unavailability.

## Conclusion

The Sofya Transcription SDK provides comprehensive error handling to ensure a robust and reliable transcription experience. By following the best practices outlined in this document, you can effectively handle errors and provide a better user experience.