Efficient way to handle errors instead of match?

If I have the following code:

let json = match serde_json::from_str::<serde_json::Value>(&*response).unwrap();

This can panic the thread if it fails due to .unwrap(). So I write:

        let json = match serde_json::from_str::<serde_json::Value>(&*response) {
            Ok(js) => js,
            Err(_) => { return Err("JSON Error".into()); }
        };

Is there a shorter and more elegant way to do this?

If the error type of the outer function supports conversion from serde_json::Error then you can use serde_json::from_str::<serde_json::Value>(&*response)?. The ? at the end is special syntax, where expr? expands (roughly) to:

match expr {
    Ok(val) => val,
    Err(e) => return Err(e.into()),
}
1 Like

If you want to continue discarding the original error you can

let json = serde_json::from_str::<serde_json::Value>(&*response)
    .map_err(|_| "JSON Error")?;
1 Like