SuperAPI AI 工具集

debugging and troubleshooting

编程与开发

查看项目

更新于 10-16 04:42

技能介绍

用途

该技能用于 Rust 代码的系统化错误诊断与调试。当代码不能正常工作、测试失败或出现运行时错误时使用,提供从错误分类到根因定位、再到解决和防回归的工作流。

主要能力

触发场景

  • 代码无法正常运行("this code isn't working")
  • 测试失败("why is this test failing?")
  • 错误解析("debug this error")
  • 编译错误("compilation error")
  • 运行时错误("runtime panic")

错误分类与诊断命令

  • 编译错误:症状为 error[E####],使用 cargo check,优先级高
  • 测试失败:症状为 test ... FAILED,使用 cargo test -- --nocapture,优先级高
  • 运行时 panic:症状为 thread 'main' panicked,使用 RUST_BACKTRACE=1,优先级高
  • 逻辑错误:症状为输出与预期不一致,使用 dbg!() 与日志,优先级中
  • 性能问题:症状为速度慢、占用内存大,使用 cargo bench、valgrind,优先级中
  • 集成错误:症状为外部服务失败,使用网络诊断,优先级低

使用方式

编译错误处理模式

  1. 查看错误:cargo check 2>&1 | head -50
  2. 解析错误码:E0277 表示 Trait 未实现,E0412 表示类型未定义,E0433 表示模块未解析
  3. 获取详细信息:rustc --explain E0277

常见错误与解决:

  • E0277:Trait 未实现,使用 #[derive(...)] 或手动实现
  • E0412:找不到类型,添加 use 语句
  • E0433:模块解析失败,确认路径与 mod 声明
  • E0502:借用冲突,检查借用作用域
  • E0382:所有权移动后使用,使用 clone() 或引用

测试失败处理模式

  1. 定位失败测试:cargo test 2>&1 | grep FAILED
  2. 以详细输出运行:cargo test test_name -- --nocapture
  3. 顺序执行以规避并行问题:cargo test -- --test-threads=1
  4. 断言细节:推荐使用 pretty_assertions、insta

运行时 panic 处理模式

  1. 获取回溯:RUST_BACKTRACE=1 cargo run
  2. 完整回溯:RUST_BACKTRACE=full cargo run
  3. 定位 panic 位置:查看 at src/lib.rs:42:5
  4. 使用调试器:rust-lldb target/debug/miyabi

逻辑错误处理模式

  • 使用 dbg! 宏:let result = dbg!(compute_value());
  • 使用 tracing:tracing::debug!(?value, "computed value");
  • 条件日志:if cfg!(debug_assertions) { println!("Debug: {:?}", state); }

高级调试工具

  • rust-lldb:调试器,rust-lldb target/debug/miyabi
  • cargo-expand:宏展开,cargo expand
  • cargo-asm:查看汇编,cargo asm
  • valgrind:内存诊断,valgrind ./target/debug/miyabi
  • miri:检测未定义行为,cargo +nightly miri test

VS Code 调试配置示例: { "type": "lldb", "request": "launch", "name": "Debug Miyabi", "cargo": { "args": ["build", "--bin=miyabi"] }, "args": [], "cwd": "${workspaceFolder}" }

常见 panic 处理

  • unwrap() on None:Option 未处理,使用 if let Some / ?
  • unwrap() on Err:Result 未处理,使用 match / ?
  • index out of bounds:数组越界,使用 .get() / 边界检查
  • overflow:算术溢出,使用 checked_* / wrapping_*
  • stack overflow:无限递归,检查递归逻辑

适用场景

适用于 Rust 项目的编译阶段、测试阶段与运行阶段排障,尤其适合需要结构化排查而非零散调试的开发者。

成功标准

  • 错误分类准确
  • 根因定位清晰
  • 给出具体修复方法
  • 添加测试以防复发

相关技能

  • Rust Development:构建与测试
  • Performance Analysis:性能问题
  • Security Audit:安全问题