Skip to main content

Error Recovery

Patterns for handling errors and recovering gracefully.

Retry Pattern

async function createSessionWithRetry(maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
await session.createSession({
avatarId: 'avatar-123',
videoContainerId: 'avatar-container',
});
return; // Success!
} catch (error) {
console.log(`Attempt ${attempt} failed:`, error.message);

if (attempt === maxRetries) {
throw error; // Give up
}

// Wait before retry (exponential backoff)
await new Promise((r) => setTimeout(r, 1000 * Math.pow(2, attempt - 1)));
}
}
}

Connection Failure Recovery

session.on('connectionChange', async (state) => {
if (state === 'FAILED') {
console.log('Connection failed, attempting recovery...');

// Try to reconnect
try {
await session.endSession();
await createSessionWithRetry();
} catch (error) {
console.error('Recovery failed:', error);
showErrorToUser('Connection lost. Please refresh the page.');
}
}
});

Complete Error Handling

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

async function robustAvatarInit() {
const session = new KalturaAvatarSession(apiKey, { baseUrl });

session.on('error', (error) => {
handleError(error);
});

try {
await session.createSession({
avatarId: 'avatar-123',
videoContainerId: 'avatar-container',
});
} catch (error) {
if (error instanceof AvatarError) {
handleAvatarError(error);
} else {
handleGenericError(error);
}
}
}

function handleAvatarError(error) {
switch (error.code) {
case AvatarErrorCode.RTC_CONNECTION_FAILED:
showError('Connection failed. Check your network and firewall settings.');
break;
case AvatarErrorCode.UNAUTHORIZED:
showError('Authentication failed. Please log in again.');
break;
default:
showError(`Error: ${error.message}`);
}
}

See Also