| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- 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<string, any>
- constructor(code: SttErrorCode, message: string, details?: Record<string, any>) {
- 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<string, any> {
- 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<T>(
- operation: () => Promise<T>,
- shouldRetry?: (error: SttError) => boolean
- ): Promise<T> {
- 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<void> {
- return new Promise((resolve) => setTimeout(resolve, ms))
- }
- }
|