rustserderust-result

How can I return an error from Serde in a function that returns Result<() , Error>


I am attempting to return an error from Serde with a function that returns Result<(), Error>:

use std::io::{Error};

#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Mine {
    ab: u8,
    ac: u8,
}
#[macro_use]
extern crate serde_derive;

fn main() {
    if do_match().is_ok() {
        println!("Success");
    }
}

fn do_match() -> Result<(), Error> {
    match serde_json::from_str::<Mine>("test") {
        Ok(_e) => println!("Okay"),
        Err(e) => return e,
    }
    Ok(())
}

Rust Playground

After various attempts, I have been unable to correct the problem to return an error, how can I do this?


Solution

  • Firstly, you are using the wrong error type. serde_json::from_str's Err is of type serde_json::error::Error whereas you are using std::io::Error. Secondly, by pattern matching on Err(e) and then trying to return e, you are no longer return a Result but instead trying to just return something of type serde_json::error::Error. Instead, you should be returning Result<(), serde_json::error::Error>. Here is the proper way to accomplish what you are trying to achieve:

    fn do_match() -> Result <(), serde_json::error::Error> {
        serde_json::from_str::<Mine>("test").map(|_| println!("Okay"))
    }
    

    map will only perform the println!(...) on the result from serde_json::from_str if it is an Ok variant, otherwise, it will just pass through the Err variant. Then, you can just return the resulting expression.

    Rust Playground