Rust Error Handling

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. }
  • Rust functions that return Result are translated to exceptions on the C++ side.
  • The exception thrown will always be of type rust::Error, which primarily exposes a way to get the error message string. The error message will come from the error type’s Display impl.
  • A panic unwinding from Rust to C++ will always cause the process to immediately terminate.