stacked_get

Macro stacked_get 

Source
macro_rules! stacked_get {
    ($value:ident [$inx0:expr] $([$inx1:expr])*) => { ... };
}
Expand description

Applies get and stack_err_with(...)? in a chain, this is compatible with many things.

use serde_json::Value;
use stacked_errors::{ensure, stacked_get, Result, StackableErr};

let s = r#"{
    "Id": "id example",
    "Created": 2023,
    "Args": [
        "--entry-name",
        "--uuid"
    ],
    "State": {
        "Status": "running",
        "Running": true
    }
}"#;

fn ex0(s: &str) -> Result<()> {
    let value: Value = serde_json::from_str(s).stack()?;

    // the normal `Index`ing of `Values` panics, this
    // returns a formatted error
    ensure!(stacked_get!(value["Id"]) == "id example");
    ensure!(stacked_get!(value["Created"]) == 2023);
    ensure!(stacked_get!(value["Args"][1]) == "--uuid");
    ensure!(stacked_get!(value["State"]["Status"]) == "running");
    ensure!(stacked_get!(value["State"]["Running"]) == true);

    Ok(())
}

ex0(s).unwrap();

fn ex1(s: &str) -> Result<()> {
    let value: Value = serde_json::from_str(s).stack()?;

    let _ = stacked_get!(value["State"]["nonexistent"]);

    Ok(())
}

assert!(ex1(s).is_err());