---
title: Error Handling
url: https://docs.kaltura.com/docs/conversational-agents/agentic-avatars-sdk/client-sdk-error-handling
---

## Error Handling

Learn how to handle errors gracefully in the Kaltura Avatar SDK.

### Error Types

All SDK errors are instances of `AvatarError` with a specific error code:

```typescript
class AvatarError extends Error {
  code: AvatarErrorCode;
  message: string;
  details?: any;
}
```

### Error Codes

| Code | Description |
|------|-------------|
| `INVALID_STATE` | Method called in wrong state |
| `API_REQUEST_FAILED` | API request failed |
| `RTC_CONNECTION_FAILED` | WebRTC connection failed |
| `INVALID_CONFIGURATION` | Invalid configuration provided |
| `SESSION_NOT_FOUND` | Session not found |
| `UNAUTHORIZED` | Authentication failed |

### Basic Error Handling

#### Try-Catch

```javascript
import { KalturaAvatarSession, AvatarError } from '@unisphere/models-sdk-js';

try {
  await session.sayText('Hello');
} catch (error) {
  if (error instanceof AvatarError) {
    console.error('Avatar error:', error.code, error.message);
  } else {
    console.error('Unexpected error:', error);
  }
}
```

#### Error Events

```javascript
session.on('error', (error) => {
  console.error('Error event:', error.code, error.message);
  // Update UI to show error
  showErrorMessage(error.message);
});
```

### Handling Specific Errors

#### Invalid State

```javascript
try {
  await session.sayText('Hello');
} catch (error) {
  if (error.code === 'INVALID_STATE') {
    console.log('Session not ready. Current state:', session.getSessionState());
    // Wait for session to be ready
    await waitForReady();
    await session.sayText('Hello');
  }
}
```

#### API Request Failed

```javascript
try {
  await session.createSession({ visualId: 'visual-123' });
} catch (error) {
  if (error.code === 'API_REQUEST_FAILED') {
    console.log('API request failed, retrying...');
    await new Promise((r) => setTimeout(r, 2000));
    await session.createSession({ visualId: 'visual-123' });
  }
}
```

#### RTC Connection Failed

```javascript
try {
  await session.createSession({ visualId: 'visual-123' });
} catch (error) {
  if (error.code === 'RTC_CONNECTION_FAILED') {
    console.log('WebRTC connection failed. Check firewall/network.');
    // Try with relay-only mode
    const newSession = new KalturaAvatarSession({
      apiKey: 'your-api-key',
      baseUrl: '...',
      iceTransportPolicy: 'relay', // Force TURN servers
    });
    await newSession.createSession({ visualId: 'visual-123' });
  }
}
```

#### Unauthorized

```javascript
try {
  await session.createSession({ visualId: 'visual-123' });
} catch (error) {
  if (error.code === 'UNAUTHORIZED') {
    console.error('Invalid API key or expired token');
    // Redirect to login or refresh token
  }
}
```

### Complete Error Handling Example

```typescript
import { KalturaAvatarSession, AvatarError, AvatarErrorCode } from '@unisphere/models-sdk-js';

async function initAvatarWithErrorHandling() {
  const session = new KalturaAvatarSession({
    apiKey: 'your-api-key',
    baseUrl: 'https://api.avatar.us.kaltura.ai/',
    retryConfig: {
      maxAttempts: 3,
      initialDelayMs: 500,
      maxDelayMs: 5000,
      backoffMultiplier: 2,
    },
  });

  // Global error handler
  session.on('error', (error: AvatarError) => {
    console.error('SDK Error:', error.code, error.message);
    document.getElementById('error-banner').textContent = error.message;
    document.getElementById('error-banner').style.display = 'block';
  });

  try {
    await session.createSession({
      visualId: 'visual-123',
      voiceId: 'voice-456',
      videoContainerId: 'avatar-container',
    });

    console.log('Avatar created successfully');
  } catch (error) {
    if (error instanceof AvatarError) {
      handleAvatarError(error);
    } else {
      console.error('Unexpected error:', error);
      showGenericError();
    }
  }
}

function handleAvatarError(error: AvatarError) {
  switch (error.code) {
    case AvatarErrorCode.INVALID_STATE:
      console.log('Wrong state - create session first');
      showError('Please start a session first');
      break;

    case AvatarErrorCode.API_REQUEST_FAILED:
      console.log('API request failed - check network');
      showError('Network error. Please check your connection.');
      enableRetryButton();
      break;

    case AvatarErrorCode.RTC_CONNECTION_FAILED:
      console.log('WebRTC connection failed');
      showError('Connection failed. This may be due to firewall settings.');
      showTroubleshootingLink();
      break;

    case AvatarErrorCode.UNAUTHORIZED:
      console.log('Authentication failed');
      showError('Authentication failed. Please log in again.');
      redirectToLogin();
      break;

    case AvatarErrorCode.SESSION_NOT_FOUND:
      console.log('Session not found or expired');
      showError('Session expired. Please create a new session.');
      enableRestartButton();
      break;

    default:
      console.log('Unknown error:', error.message);
      showError(`Error: ${error.message}`);
  }
}

function showError(message: string) {
  const errorEl = document.getElementById('error-message');
  errorEl.textContent = message;
  errorEl.style.display = 'block';
}
```

### Best Practices

#### 1. Always Use Try-Catch

```javascript
// Bad
await session.sayText('Hello');

// Good
try {
  await session.sayText('Hello');
} catch (error) {
  console.error('Failed to speak:', error);
}
```

#### 2. Provide User Feedback

```javascript
try {
  showLoading();
  await session.createSession({ ... });
  hideLoading();
} catch (error) {
  hideLoading();
  showError('Failed to create session. Please try again.');
}
```

#### 3. Log Errors for Debugging

```javascript
session.on('error', (error) => {
  // Log to your error tracking service
  logToSentry(error);
  console.error('Error:', error);
});
```

### Next Steps

- **[Advanced Usage](./client-sdk-advanced)** - Custom ICE servers and more
- **Troubleshooting Guide** - Common issues and solutions
