Skip to content

8. 错误处理与恢复

8.1 优雅的错误处理

typescript
class ErrorHandler {
  async handle(error: Error, context: ExecutionContext) {
    // 分类错误
    const category = this.categorize(error);
    
    switch (category) {
      case 'permission_denied':
        return {
          message: "Permission denied. Would you like to grant access?",
          recoverable: true,
          action: async () => {
            const granted = await requestPermission();
            if (granted) {
              return await retry(context);
            }
          }
        };
        
      case 'file_not_found':
        return {
          message: `File not found: ${error.path}`,
          recoverable: true,
          suggestions: await this.findSimilarFiles(error.path)
        };
        
      case 'network_error':
        return {
          message: "Network error. Check your connection.",
          recoverable: true,
          action: async () => {
            await sleep(2000);
            return await retry(context);
          }
        };
        
      default:
        return {
          message: `Error: ${error.message}`,
          recoverable: false
        };
    }
  }
}

8.2 变更回滚

typescript
class ChangeTracker {
  private changes: FileChange[] = [];
  
  record(change: FileChange) {
    this.changes.push({
      ...change,
      timestamp: Date.now(),
      backup: change.type !== 'create' ? change.originalContent : null
    });
  }
  
  async undo(count: number = 1) {
    const toUndo = this.changes.slice(-count);
    
    for (const change of toUndo.reverse()) {
      switch (change.type) {
        case 'create':
          await fs.unlink(change.path);
          break;
        case 'modify':
          await fs.writeFile(change.path, change.backup!);
          break;
        case 'delete':
          await fs.writeFile(change.path, change.backup!);
          break;
      }
    }
    
    this.changes = this.changes.slice(0, -count);
  }
  
  getSummary(): string {
    const recent = this.changes.slice(-10);
    return recent.map(c => 
      `${c.timestamp}: ${c.type} ${c.path}`
    ).join('\n');
  }
}

9. 关键设计启示

9.1 设计原则

  1. 显式权限: 所有写操作都需要确认
  2. 沙箱隔离: 默认最小权限运行
  3. 持久记忆: 跨会话保持上下文
  4. 任务追踪: 复杂任务拆分为可追踪的步骤
  5. 可恢复: 所有变更可撤销

9.2 值得借鉴的模式

typescript
// 1. 分层权限
const permissionLevels = {
  auto: ['read_file', 'list_dir', 'grep', 'search'],
  confirm: ['write_file', 'edit_file', 'run_cmd'],
  explicit: ['network', 'git_write', 'system']
};

// 2. 沙箱执行
async function sandboxedExecute(cmd, permissions) {
  const sandbox = await createSandbox(permissions);
  return sandbox.run(cmd);
}

// 3. 变更追踪
class UndoStack {
  push(change) { this.changes.push(change); }
  undo() { 
    const change = this.changes.pop();
    return this.reverse(change);
  }
}

// 4. 记忆检索
class Memory {
  async recall(query) {
    return this.store
      .filter(m => this.matches(m, query))
      .slice(0, 5);
  }
}

延伸阅读

前端面试知识库