Rust Error Handling

  1. #[cxx::bridge]
  2. mod ffi {
  3. extern "Rust" {
  4. fn fallible(depth: usize) -> Result<String>;
  5. }
  6. }
  7. fn fallible(depth: usize) -> anyhow::Result<String> {
  8. if depth == 0 {
  9. return Err(anyhow::Error::msg("fallible1 requires depth > 0"));
  10. }
  11. Ok("Success!".into())
  12. }
  • 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.