Errors handling parsing JSON


#1

Hi everyone.
To tell the truth its pretty sad that Rust doesnt have try{}catch{} handlers, i terribly need an example of handling the error if the incoming string is not a JSON string. For example i have next:

let mut string=String::new();
std::io::stdin().read_line(&mut string);
string.pop();
let value:Value=serde_json::from_str(&string)// thats where i need to catch an error if string was not in JSON format.


#2

I don’t fully understand:

let value:Value=serde_json::from_str(&string);

This isn’t the correct type. The return type from from_str is serde_json::Result. https://docs.serde.rs/serde_json/type.Result.html

From here, you can easily manage the error directly:

let res = serde_json::from_str(&string);

match res {
    Ok(v) => { do_something(v) },
    Err(e) => { //handle error },
}

Other ways, like using try!/? Result combinators like and_then are also possible.


#3

Thank you Sir.
It was me who probably mixed eveerything up, trying to handle parsing errors. Now everything is clear and finally works. Thanks.


#4

No problem, happy to be of help.