Rust 错误处理

#[cxx::bridge] mod ffi { extern "Rust" { fn fallible(depth: usize) -> Result<String>; } } fn fallible(depth: usize) -> anyhow::Result<String> { if depth == 0 { return Err(anyhow::Error::msg("fallible1 requires depth > 0")); } Ok("Success!".into()) }

Speaker Notes

  • 在 C++ 方面,返回 Result 的 Rust 函数会被翻译为异常。
  • 抛出的异常始终是 rust::Error 类型,该类型主要用于提供获取错误消息字符串的方法。错误消息将由错误类型的 Display impl 提供。
  • 当 panic 从 Rust 展开到 C++ 时,会始终导致进程立即终止。