Rust 错误处理

1. #[cxx::bridge]
2. mod ffi {
3. extern "Rust" {
4. fn fallible(depth: usize) -> Result<String>;
5. }
6. }

8. fn fallible(depth: usize) -> anyhow::Result<String> {
9. if depth == 0 {
10. return Err(anyhow::Error::msg("fallible1 requires depth > 0"));
11. }

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