Errors handling parsing JSON

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);
let value:Value=serde_json::from_str(&string)// thats where i need to catch an error if string was not in JSON format.

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.

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.

1 Like

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

No problem, happy to be of help.