expression

Tonic: return and inspect a status code

Return InvalidArgument for an invalid ID and NotFound for a valid but absent item. The example verifies the status from the local service. Real clients should distinguish status errors from transport setup failures and avoid returning sensitive internal details. Run in the accompanying generated-bindings Cargo project. Expected stdout (not executed): invalid: true missing: true Common mistake: Using Internal for ordinary bad input or including secrets in status text.

Formal Syntax & Structure

rust syntaxrust
Status::invalid_argument(message); status.code()

Working Example

Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() {    use bm_tonic_inventory::{InventoryDemo, pb::{GetItemRequest, inventory_server::Inventory}};    use tonic::{Request, Code};    let err = InventoryDemo.get_item(Request::new(GetItemRequest { id: 0 })).await.unwrap_err();    println!("invalid: {}", err.code() == Code::InvalidArgument);    let err = InventoryDemo.get_item(Request::new(GetItemRequest { id: 9 })).await.unwrap_err();    println!("missing: {}", err.code() == Code::NotFound);}
Rust Reference