export type SttErrorCode = | 'NOT_INITIALIZED' | 'NOT_JOINED' | 'INVALID_CONFIG' | 'INVALID_LANGUAGES' | 'ALREADY_JOINED' | 'NETWORK_ERROR' | 'AUTHENTICATION_ERROR' | 'PERMISSION_DENIED' | 'TIMEOUT' | 'UNKNOWN_ERROR' | 'APP_ID_REQUIRED' export class SttError extends Error { public readonly code: SttErrorCode public readonly timestamp: number public readonly details?: Record constructor(code: SttErrorCode, message: string, details?: Record) { super(message) this.name = 'SttError' this.code = code this.timestamp = Date.now() this.details = details // 保持正确的原型链 Object.setPrototypeOf(this, SttError.prototype) } static fromError(error: unknown, code: SttErrorCode = 'UNKNOWN_ERROR'): SttError { if (error instanceof SttError) { return error } if (error instanceof Error) { return new SttError(code, error.message, { originalError: error }) } return new SttError(code, String(error)) } toJSON(): Record { return { name: this.name, code: this.code, message: this.message, timestamp: this.timestamp, details: this.details, stack: this.stack, } } toString(): string { return `[${this.code}] ${this.message}` } } // 错误处理工具函数 export const createErrorHandler = (emitter?: { emit: (event: string, error: Error) => void }) => { return (error: unknown, context?: string): SttError => { const sttError = SttError.fromError(error) if (context) { Object.assign(sttError, { details: { ...sttError.details, context, }, }) } // 如果提供了事件发射器,发送错误事件 if (emitter) { emitter.emit('error', sttError) } console.error(`[STT SDK Error] ${sttError.toString()}`, sttError.details) return sttError } } // 错误恢复策略 export class ErrorRecovery { private maxRetries: number private retryDelay: number constructor(maxRetries = 3, retryDelay = 1000) { this.maxRetries = maxRetries this.retryDelay = retryDelay } async retry( operation: () => Promise, shouldRetry?: (error: SttError) => boolean ): Promise { let lastError: SttError = new SttError('UNKNOWN_ERROR', 'Operation failed') for (let attempt = 1; attempt <= this.maxRetries; attempt++) { try { return await operation() } catch (error) { const sttError = SttError.fromError(error) lastError = sttError // 检查是否应该重试 if (shouldRetry && !shouldRetry(sttError)) { break } // 检查是否达到最大重试次数 if (attempt === this.maxRetries) { break } // 等待一段时间后重试 await this.delay(this.retryDelay * attempt) } } throw lastError } private delay(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)) } }