Skip to main content

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:

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

Error Codes

CodeDescription
INVALID_STATEMethod called in wrong state
API_REQUEST_FAILEDAPI request failed
RTC_CONNECTION_FAILEDWebRTC connection failed
INVALID_CONFIGURATIONInvalid configuration provided
SESSION_NOT_FOUNDSession not found
UNAUTHORIZEDAuthentication failed

Basic Error Handling

Try-Catch

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

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

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

try {
await session.createSession({ avatarId: 'avatar-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({ avatarId: 'avatar-123' });
}
}

RTC Connection Failed

try {
await session.createSession({ avatarId: 'avatar-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('your-api-key', {
baseUrl: '...',
iceTransportPolicy: 'relay', // Force TURN servers
});
await newSession.createSession({ avatarId: 'avatar-123' });
}
}

Unauthorized

try {
await session.createSession({ avatarId: 'avatar-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

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

async function initAvatarWithErrorHandling() {
const session = new KalturaAvatarSession('your-api-key', {
baseUrl: 'https://api.avatar.us.kaltura.ai/v1/avatar-session',
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({
avatarId: 'avatar-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

// ❌ Bad
await session.sayText('Hello');

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

2. Provide User Feedback

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

3. Log Errors for Debugging

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

Next Steps